javascript/jquery范围让我难过

use*_*715 2 javascript jquery scope

我已将一个常见的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;

}
Run Code Online (Sandbox Code Playgroud)

ajax()调用中的alert()显示json对象,但是如果在函数外部尝试并发出警报,和/或从ajax()调用内部返回响应,则其值为null?!

任何帮助/指针将不胜感激.

Fel*_*ing 9

典型的错误.Ajax调用后的代码

alert(output);
return json;
Run Code Online (Sandbox Code Playgroud)

在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
         }
   });   
}
Run Code Online (Sandbox Code Playgroud)

然后:

queryCostCenter(some_value, some_value, some_value, function(result) {
    // do something with the returned data.
});
Run Code Online (Sandbox Code Playgroud)

或者将所有逻辑放在Ajax调用的成功处理程序中.但是使用回调函数,您可以更灵活,并且可以更好地重用该函数.


这是回调的一个非常常见的用例.由于您不知道何时完成Ajax调用,因此将函数传递给应该运行的Ajax调用,此时返回一些结果.您对success处理程序没有任何其他操作:它是一个在调用完成时调用的函数.


归档时间:

查看次数:

461 次

最近记录:

15 年,4 月 前