jQuery getJSON 将结果保存到变量中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15764844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:45:45  来源:igfitidea点击:

jQuery getJSON save result into variable

javascriptjqueryjson

提问by user1229351

I use getJSON to request a JSON from my website. It works great, but I need to save the output into another variable, like this:

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

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

                 });

I need to save the result into myjsonbut it seems this syntax is not correct. Any ideas?

我需要将结果保存到,myjson但似乎这种语法不正确。有任何想法吗?

采纳答案by webdeveloper

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

调用时无法获取值getJSON,只能在响应后获取。

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

回答by Ravi Gadag

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

$.getJSon 需要一个回调函数,要么将其传递给回调函数,要么在回调函数中将其分配给全局变量。

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.

IMO 最好是调用回调函数。这对眼睛更好,可读性方面。

$.getJSON("http://127.0.0.1:8080/horizon-update", callbackFuncWithData);

function callbackFuncWithData(data)
{
 // do some thing with data 
}