如何将 JSON 响应保存到 JavaScript/jQuery 中的全局变量以供稍后使用。我尝试了多种方法,包括保存从调用返回的响应文本(data.responseText),但最后它仍然是空/未定义。 我知道强烈建议不要将响应保存在 DOM 元素中。我不想每次需要特定数据时都进行相同的调用。有没有简单的方法可以在ajax成功回调函数之外访问它?
我尝试过的:
$('#pay-now').click(function(e){
e.preventDefault();
data = '';
var myResponse;
var orderObj = {
addr_id: addr_id,
cust_email: cust_email,
total_amt_to_pay: total_amt_to_pay,
items_bought: items_bought,
shipping: shipping,
coupon_code: coupon,
trx_id: trx_id
};
// Send the data to save using post
var posting = $.post( '../inc/payment/pay_with_card.php', orderObj );
posting.done(function( data ) {
/* check result from the attempt */
data = data;
console.log(data);
payWithPaystack(data);
});
posting.fail(function( data ) { /* and if it failed... */ });
//}
});
function payWithPaystack(data){
var handler = PaystackPop.setup({
key: '<?php //echo PAYSTACK_PUBLIC_KEY; ?>',
email: data.email,
amount: data.price,
metadata: {
cartid: data.sessionId,
orderid: data.sessionId,
custom_fields: [
{
display_name: "Paid on",
variable_name: "paid_on",
value: 'Website'
},
{
display_name: "Paid via",
variable_name: "paid_via",
value: 'Inline Popup'
}
]
},
callback: function(response){
// post to server to verify transaction before giving value
var verifying = $.get( '/verify.php?reference=' + response.reference);
verifying.done(function( data ) { /* give value saved in data */ });
},
onClose: function(){
alert('Click "Pay now" to retry payment.');
}
});
handler.openIframe();
}
最佳答案
只需在任何函数之外声明它即可:
var dataStore;
$('#pay-now').click(function(e) {
e.preventDefault();
//...
posting.done(function(data) {
dataStore = data;
//...
}
//...
});
关于javascript - 如何将 ajax json 响应保存到全局变量以供重用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61023656/