gpt4 book ai didi

javascript - 如何将数据从ajax传递到django View ?

转载 作者:行者123 更新时间:2023-12-02 19:04:01 26 4
gpt4 key购买 nike

我有以下 ajax 脚本。这会获取公钥并将所有其他详细信息发送到 Stripe 服务器进行付款,但我需要将价格的动态值发送到 item_line。

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);
});
});
}
});

如何通过以及如何在 View 文件中捕获?我目前的看法是:


@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:
...

}

views.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)

关于javascript - 如何将数据从ajax传递到django View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65309532/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com