将json加载到变量中 [英] load json into variable

查看:57
本文介绍了将json加载到变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须做一些非常简单的事情,但是据我所知,似乎没有一种简单的方法可以做到这一点.我只想从远程源加载JSON数据,然后使用jQuery将其存储在全局Javascript变量中.这就是我所拥有的:

I have to do something very simple, but there doesn't seem to be an easy way to do this, as far as I can tell. I just want to load JSON data from a remote source and store it in a global Javascript variable using jQuery. Here's what I have:

var my_json;
$.getJSON(my_url, function(json) {
  var my_json = json;
});

my_json变量保持未定义.我认为这显然是一个范围问题.在我看来,$ .getJSON方法应该返回JSON,但它返回一个XMLHttpRequest对象.如果我这样做:

The my_json variable remains undefined. I think this is clearly a scope issue. It seems to me the $.getJSON method should return JSON, but it returns an XMLHttpRequest object. If I do this:

request = $.getJSON(my_url);
my_json = request.responseText.evalJSON();

那是行不通的,因为直到readystate == 4为止,responsetext仍为null.似乎您必须使用回调函数来返回响应文本,因为它会在成功时触发.

That doesn't work because until the readystate == 4, the responsetext remains null. It seems you have to use the callback function to return the responsetext, since it fires on success.

这很难!对吧?

推荐答案

这可以做到:

var json = (function () {
    var json = null;
    $.ajax({
        'async': false,
        'global': false,
        'url': my_url,
        'dataType': "json",
        'success': function (data) {
            json = data;
        }
    });
    return json;
})(); 

主要问题是$.getJSON将异步运行,因此,即使在success回调触发之前,您的Javascript也会经过调用它的表达式,因此不能保证您的变量将捕获任何数据.

The main issue being that $.getJSON will run asynchronously, thus your Javascript will progress past the expression which invokes it even before its success callback fires, so there are no guarantees that your variable will capture any data.

请特别注意上述ajax调用中的'async': false选项. 手册说:

Note in particular the 'async': false option in the above ajax call. The manual says:

默认情况下,所有请求均已发送 异步(即,将其设置为true 默认).如果需要同步 请求,请将此选项设置为false. 请注意,同步请求可能会 暂时锁定浏览器, 禁用任何操作,而 请求处于活动状态.

By default, all requests are sent asynchronous (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

这篇关于将json加载到变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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