我已经将一个常见的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?!
如有任何帮助或建议,将不胜感激。
发布于 2010-10-12 05:47:14
典型的错误。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调用,当返回一些结果时,应该运行该函数。您没有对success处理程序做任何其他事情:它是一个在调用完成时调用的函数。
发布于 2010-10-12 05:46:28
$.ajax()是异步的。简而言之:函数块外的警告(输出)很可能在async方法返回任何结果之前被调用,因此仍为空。
发布于 2010-10-12 05:48:20
这不是范围问题。这是Ajax调用的异步本质。在Ajax success处理程序运行之前,您的queryCostCenter函数可能会返回。您需要在success回调中启动所有后Ajax逻辑。
https://stackoverflow.com/questions/3910169
复制相似问题