开发者

How can I return value from $.getJSON function? [duplicate]

This question already has an answer here: Closed 11 years ago.

Possible Duplicate:

How to return value from $.getJSON

        function get_url(){
            var returnValue  = null;
            $.getJSON('http://127.0.0.1:1337/?callback=?&command=get_url', "", function(data){
                data = $.parseJSON(data);
                returnValue = data[0].get_url;
                console.log(returnValue); // "not_null"

            }); 
            console.log(returnValue);  // "null"
            return returnValue;
        开发者_JAVA百科}

Why function don't return "not_null" ?


The call to $.getJSON is asynchronous and won't have completed before your get_url function has returned. There won't be a value in returnValue to return.

You need to either make the call synchronous by using $.ajax with async:false rather than $.getJSON or handle the return value in an asynchronous manner, modifying the calling logic to not expect it straight away.

$.getJSON

is simply shorthand for a call to $.ajax, so you can do this instead:

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  async: false,
  success: callback
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜