views:

83

answers:

2
function json (url){
       $.getJSON(url, function(data) {
           return data;
       })
   }

this function don't see "data"

function MakeAlert(){
       data = json('action.php');
       window.alert(data.name);
}

this work:

  function json (url){
           $.getJSON(url, function(data) {
               window.alert(data.name);
           })
  }
+2  A: 

That's because the $.getJSON is asynchronous. It sends the request and returns immediately. Once the server responds (which might be a few seconds later) it invokes the success callback and that's why the data is accessible only inside this callback.

If you want to block the caller you could send a synchronous request (note that this might freeze the UI while the request is executing which defeats the whole purpose of AJAX):

function json(url) {
    var result = null;
    $.ajax({
        url: url,
        async: false,
        dataType: 'json',
        success: function(data) {
            result = data;
        }
    });
    return result;
}
Darin Dimitrov
Thank you. now become clear
+1  A: 
function json (url){
   $.getJSON(url, function(data) {
       return data;
   })
}

You cannot use return here. You would return data the to anonymous closure function.

Your best shot is to use a callback function which should be applied when the getJSON success handler is executed.

function json (url, cb){
   $.getJSON(url, function(data) {
       cb.apply(null, [data]);
   })
}

usage

json('action.php', function(data){
    alert(data);
});
jAndy