如何在jQuery中存储JSON响应? [英] How to store JSON response in jQuery?
问题描述
我想将json响应存储在一个全局变量中,因此,我可以通过我的应用程序使用它,而不必多次执行getJSON请求.
I'd like to store my json response in a global variable so, i could use it through my app without making a getJSON request more than once.
var data;
$.getJSON("panorama.json",function(json){
data = json.images[0].src;
console.log(data);
});
console.log(data);
如果我将其记录在实际请求中很好,但在其他任何地方都得到未定义". 任何评论.
If I log it in the actual request its fine, but i get "undefined" everywhere else. Any comment appriciated.
编辑[从评论中复制]:已尝试...
Edit [copied from comments]: Tried ...
$.myglobals = { result: "unset" }
$(document).ready(function() {
$.getJSON( "panorama.json", function(json) {
$.myglobals.result = json.images[0].src;
console.log($.myglobals.result);
});
console.log($.myglobals.result);
}) ;
第一个日志可以,第二个未定义.
The first log is okay, the second is undefined.
编辑[从答案中复制]:
Edit [copied from answer]:
实际上两种方法都有效
actually both method worked
有趣的是,我的 请求是在一个功能,我试过 访问我的全局变量权限 在相同功能的请求之后
the interesting thing is that my request was in a function and i tried to acces my global variable right after the request in the same function
当我在功能之外访问时 它像魅力一样工作
when i accesed it outside the function it worked like a charm
推荐答案
如果您的真实代码具有这种结构,那么尝试访问尚未设置的数据就会遇到问题还 .仅仅因为您的$.getJSON()
高于console.log()
并不意味着您在记录数据值之前就得到了响应.
If your real code is structured like that then you have a problem with trying to access the data that hasn't been set yet. Just because your $.getJSON()
is above console.log()
doesn't mean that you get the response before you log value of data.
因此,您的问题不是范围,而是时机:引入一些服务器端滞后,您的解决方案也可能崩溃.
So your problem is not scope, but rather the timing: introduce some server-side lag and your solution may as well crash.
如果收到响应,也许您应该设置一些标志:
Maybe you should set some flag if response was received:
var data, dataReceived = false;
$.getJSON("panorama.json",function(json){
data = json.images[0].src;
dataReceived = true;
console.log(data);
});
// somwhere later
if (dataReceived) {
console.log(data);
} else {
// you could use setTimeout() or setInterval here to re-check
console.log("data not received yet");
}
这篇关于如何在jQuery中存储JSON响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!