如何在 jQuery 中存储 JSON 响应? [英] How to store JSON response in jQuery?

查看:30
本文介绍了如何在 jQuery 中存储 JSON 响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将我的 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);

如果我将它记录在实际请求中它很好,但我在其他任何地方都得到未定义".任何评论appriciated.

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.

编辑[从答案复制]:

实际上这两种方法都有效

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆