jQuery 将 json 加载到变量中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2177548/
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 12:56:30  来源:igfitidea点击:

load json into variable

jqueryjsongetjson

提问by Aaron

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:

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

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

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:

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

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

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.

这不起作用,因为在 readystate == 4 之前,响应文本保持为空。似乎您必须使用回调函数来返回响应文本,因为它会在成功时触发。

It can't be this hard! Right?

不可能这么难!对?

回答by karim79

This will do it:

这将做到:

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

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

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

Note in particular the 'async': falseoption in the above ajax call. The manualsays:

特别注意'async': false上面 ajax 调用中的选项。该手册说:

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.

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

回答by CountZero

code bit should read:

代码位应为:

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

回答by MAFAIZ

<input  class="pull-right" id="currSpecID" name="currSpecID" value="">

   $.get("http://localhost:8080/HIS_API/rest/MriSpecimen/getMaxSpecimenID", function(data, status){
       alert("Data: " + data + "\nStatus: " + status);
    $("#currSpecID").val(data);
    });

enter image description hereenter image description here

在此处输入图片说明在此处输入图片说明

回答by Rodrigo Slompo

var itens = null;
$.getJSON("yourfile.json", function(data) {
  itens = data;
  itens.forEach(function(item) {
    console.log(item);
  });
});
console.log(itens);
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
</head>
<body>
</body>
</html>

回答by Noel Sasikanth

  • this will get JSON file externally to your javascript variable.
  • now this sample_data will contain the values of JSON file.
  • 这将从外部获取 JSON 文件到您的 javascript 变量。
  • 现在这个 sample_data 将包含 JSON 文件的值。


var sample_data = '';
$.getJSON("sample.json", function (data) {
    sample_data = data;
    $.each(data, function (key, value) {
        console.log(sample_data);
    });
});