jQuery getJSON save result into variable

This question already has an answer here:

  • How do I return the response from an asynchronous call? 33 answers

  • 调用getJSON ,只有在响应后才能获得值。

    var myjson;
    $.getJSON("http://127.0.0.1:8080/horizon-update", function(json){
        myjson = json;
    });
    

    $.getJSon expects a callback functions either you pass it to the callback function or in callback function assign it to global variale.

    var globalJsonVar;
    
        $.getJSON("http://127.0.0.1:8080/horizon-update", function(json){
                   //do some thing with json  or assign global variable to incoming json. 
                    globalJsonVar=json;
              });
    

    IMO best is to call the callback function. which is nicer to eyes, readability aspects.

    $.getJSON("http://127.0.0.1:8080/horizon-update", callbackFuncWithData);
    
    function callbackFuncWithData(data)
    {
     // do some thing with data 
    }
    
    链接地址: http://www.djcxy.com/p/9480.html

    上一篇: 成功设置变量值

    下一篇: jQuery getJSON将结果保存到变量中