将结果保存为变量

我使用 getJSON 从我的网站请求 JSON。它工作得很好,但我需要将输出保存到另一个变量中,如下所示:

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


});

我需要保存结果到 myjson,但似乎这种语法是不正确的。有什么想法吗?

158230 次浏览

You can't get value when calling getJSON, only after response.

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
}