javascript / jquery范围让我难过

时间:2010-10-11 21:42:45

标签: 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;

}

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

任何帮助/指示都将不胜感激。

4 个答案:

答案 0 :(得分:9)

典型的错误。 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处理程序没有任何其他操作:它是一个在调用完成时调用的函数。

答案 1 :(得分:2)

$ .ajax()是异步的。 简而言之:在异步方法返回任何结果之前,很可能会调用功能块外部的警报(输出),因此仍为空。

答案 2 :(得分:1)

这不是范围问题。这是Ajax调用的异步特性。您的queryCostCenter函数可能会在Ajax success处理程序运行之前返回。您需要在success回调中启动所有后Ajax逻辑。

答案 3 :(得分:0)

你实际上并没有获取并转换回JSON,只是一个大文本blob。查看getJSON的文档,这是您需要使用的文档。

http://api.jquery.com/jQuery.getJSON/

$.getJSON({
     '/lib/ajax/ajax_prepaid_cost_calculator.php',
     {data:data}
     , function(data) {   
        alert(data.jsonElement);
        //do something with your data HERE

     }

});

jsonElement是JSON数组中的一个元素