如何将数据从ajax传递到django视图



我有以下ajax脚本。这将获得公钥并将所有其他细节发送到Stripe服务器进行支付,但我需要将价格的动态值发送到itemline。

fetch("/config/")
.then((result) => { return result.json();})
.then((data) => {
// Initialize Stripe.js
var data1 = $('#priceId').html();

const stripe = Stripe(data.publicKey);
// Event handler
let submitBtn = document.querySelector("#submitBtn");
if (submitBtn !== null) {
submitBtn.addEventListener("click", () => {
var d = $('#priceId').html();
console.log(d) // this value need to send to my view...

fetch("/create-checkout-session/")
.then((result) => { 
return result.json();
})
.then((data) => {
// Redirect to Stripe Checkout
return stripe.redirectToCheckout({sessionId: data.sessionId})
})
.then((res) => {
console.log(res);
});
});
}
});

如何在视图文件中传递和捕获?我目前的看法是:


@csrf_exempt
def create_checkout_session(request):
if request.method == 'GET':
domain_url = 'http://localhost:8000/'
stripe.api_key = settings.STRIPE_SECRET_KEY
try:
checkout_session = stripe.checkout.Session.create(
client_reference_id=request.user.id if request.user.is_authenticated else None,
success_url=domain_url + 'success?session_id={CHECKOUT_SESSION_ID}',
cancel_url=domain_url + 'cancel/',
payment_method_types=['card'],
mode='subscription',
line_items=[
{
'price': settings.STRIPE_PRICE_ID, # here need dynamic selected value
'quantity': 1,
}
]
)
return JsonResponse({'sessionId': checkout_session['id']})
except Exception as e:
return JsonResponse({'error': str(e)})

请帮帮我。

通过多种方式,我将给出一个简单的示例:

script.js

// wrap request in a function:
function send_data() {

$.ajax({
url : 'the_url',
data : {
'csrfmiddlewaretoken' : '<the-token>',
'key1' : 'val1',
},
method : 'POST',
success : success_function // reference to below
});
}
// trigger send_data on some event:
$('<the-selector').on('<some-event>', {}, send_data);
// i.e. send data on button click:
$('#button-id').on('click', {}, send_data);
// success function:
function success_function(response) {
// unpack response:
val2 = response.key2;
// do some logic:
...
}

视图.py

def my_view_function(request):
# unpack request from front end:
val1 = request.POST['key1']
# do some logic:
...
# pack response:
response = {
'key2' : 'val2',
}
return JsonResponse(response)

相关内容

  • 没有找到相关文章