开发者

javascript/jquery scope has me stumped

I have wrapped a common ajax call into a function. It pings a script, returns JSON.

However for the life of me I can't seem to be able to have the JSON object be the return value of the function.

Must be something fairly simple I am missing, bu for the life of me can't work it out.

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;

}

The alert() inside the ajax() call displays开发者_如何学C the json object, however if try and alert outside the function, and/or return the response from inside the ajax() call its value is null?!

Any help/pointers would be appreciated.


Typical mistake. The code after the Ajax call

alert(output);
return json;

is executed, before the Ajax call returns. It is asynchronous (meaning, it is not executed when and where you put it in the code, but at some later point in time). You can provide a callback to your function, like so:

// 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
         }
   });   
}

then:

queryCostCenter(some_value, some_value, some_value, function(result) {
    // do something with the returned data.
});

Or put all the logic in the success handler of the Ajax call. But with a callback function, you are more flexible and you can better reuse the function.


This a very common use case for callbacks. As you don't know when the Ajax call will be finished, you pass a function to the Ajax call that should be run, when some results is returned. Your are doing nothing else with the success handler: It is a function that is called when the call is finished.


$.ajax() is async. In short: the alert(output) outside your function block will most likely be called before the async method returned any result, therefor is still null.


It's not a matter of scope. It's the asynchronous nature of your Ajax call. Your queryCostCenter function will likely return before the Ajax success handler runs. You need to kick off all post-Ajax logic in your success callback.


you aren't actually fetching and converting back to JSON, just a big text blob. look at the documentation for getJSON, which is what you need to use.

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

     }

});

with jsonElement being an element in your JSON array

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜