开发者

function dont see JSON object (java script, jQuery)

开发者 https://www.devze.com 2023-01-12 15:13 出处:网络
function json (url){ $.getJSON(url, 开发者_开发知识库function(data) { return data; }) } this function don\'t see \"data\"
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);
           })
  }


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


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

精彩评论

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