我已将常见的 ajax 调用包装到一个函数中。它 ping 一个脚本,返回 JSON。
但是在我的一生中,我似乎无法让 JSON 对象成为函数的返回值。
一定是我缺少的相当简单的东西,但我一生都无法解决。
function queryCostCenter(user_id, currency_id, country_id){
var output = null;
var destinations = new Array();
var destination = { qty:1, country: country_id };
destinations.push(destination)
var data = {
destinations : $.toJSON(destinations),
user_id : user_id,
currency_id: currency_id
};
$.ajax({
data: data,
type: 'POST',
url: '/lib/ajax/ajax_prepaid_cost_calculator.php',
success: function(data) {
output = data;
alert(output);
}
});
alert(output);
return json;
}
ajax() 调用内的alert() 显示 json 对象,但是如果在函数外部尝试并发出警报,和/或从 ajax() 调用内部返回响应,其值为 null?!
任何帮助/指示将不胜感激。
最佳答案
典型的错误。 Ajax调用后的代码
alert(output);
return json;
在 Ajax 调用返回之前执行。它是异步(这意味着,它不会在您将其放入代码中的时间和位置执行,而是在稍后的某个时间点执行)。您可以为您的函数提供回调,如下所示:
// cb is our callback - it is a function
function queryCostCenter(user_id, currency_id, country_id, cb){
var destinations = new Array();
var destination = { qty:1, country: country_id };
destinations.push(destination)
var data = {
destinations : $.toJSON(destinations),
user_id : user_id,
currency_id: currency_id
};
$.ajax({
data: data,
type: 'POST',
url: '/lib/ajax/ajax_prepaid_cost_calculator.php',
success: function(result) { // or just `success: cb`
cb(result); // execute the callback with the returned data
}
});
}
然后:
queryCostCenter(some_value, some_value, some_value, function(result) {
// do something with the returned data.
});
或者将所有逻辑放在 Ajax 调用的成功处理程序中。但是使用回调函数,您会更加灵活,并且可以更好地重用该函数。
<小时/>这是回调的一个非常常见的用例。由于您不知道 Ajax 调用何时完成,因此您将一个函数传递给应该在返回某些结果时运行的 Ajax 调用。您没有对成功处理程序执行任何其他操作:它是一个在调用完成时调用的函数。
关于javascript/jquery 范围让我难住了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3910169/