Javascript 将json从文件加载到对象中

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

load json from file into object

javascriptjqueryjsonobject

提问by Slopeside Creative

Struggling to load json from file (myData.json) on URL into an object so I can access property values.

努力将 json 从 URL 上的文件 (myData.json) 加载到对象中,以便我可以访问属性值。

-- The data loads immediately, I need it a lot in the app.

-- 数据立即加载,我在应用程序中非常需要它。

-- I'm going to access the data throughout the app, not just as part of one function that happens immediately after the data loads.

-- 我将访问整个应用程序中的数据,而不仅仅是作为数据加载后立即发生的一个函数的一部分。

-- I've ensured the data in my file is properly formatted json.

-- 我已确保文件中的数据格式正确为 json。

Following the example on the jquery API, shouldn't I be able to do something simple like:

按照 jquery API 上的示例,我不应该能够做一些简单的事情,例如:

alert(jqxhr.myProperty);

警报(jqxhr.myProperty);

and get the value? What step am I missing here?I've tried running eval and a variety of things like

并获得价值?我在这里错过了什么步骤?我试过运行 eval 和各种各样的东西,比如

var myObj=JSON.parse(jqxhr);

var myObj=JSON.parse(jqxhr);

to no avail.

无济于事。

Please....thank you.

求求你了,谢谢你。

// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.getJSON("example.json", function() {
  alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });

// perform other work here ...

// Set another completion function for the request above
jqxhr.complete(function(){ alert("second complete"); });

采纳答案by Fresheyeball

I think you are making it too complicated :)

我认为你把它弄得太复杂了:)

 var JSON;

 $.getJSON('example.json', function(response){
       JSON = response;
       alert(JSON.property);
 })
 //feel free to use chained handlers, or even make custom events out of them!
 .success(function() { alert("second success"); })
 .error(function() { alert("error"); })
 .complete(function() { alert("complete"); });

the getJSON function automatically converts your response into a proper JSON object. No need to parse.

getJSON 函数会自动将您的响应转换为正确的 JSON 对象。不需要解析。

You mentioned that you are using this data all over the place, so you will have to wait for the ajax call to complete before the data is accesible. That means either wrapping your entire application in the getJSONcallback. Or using a custom event to determine like so:

你提到你到处都在使用这些数据,所以你必须等待 ajax 调用完成才能访问数据。这意味着要么将整个应用程序包装在getJSON回调中。或者使用自定义事件来确定:

 var JSON;

 $(window).on('JSONready', function(){
       alert(JSON.property);
 });

 $.getJSON('example.json', function(response){
       JSON = response;
       $(window).trigger('JSONready');
 });

 $('#elem').on('click', function(){
       //event likely to take place after ajax call has transpired
       //it would still be better to assign this listener in a callback, 
       //but you can get away with not doing it, if you put in a catch
       if(JSON){
           alert(JSON.property);
       }          
 });

EDIT

编辑

After a quick live debug, the real reason for the data being unavailable was this: javascript that consumes JSON was located in a file include the page document NORTH of inline javascript performing the call. As a result JSON was not a global variable, and scope prevented its usage. If you truly need a variable to be global so it can be used with inline JS as well as any and all included js files, you may do so like this:

经过快速实时调试后,数据不可用的真正原因是:使用 JSON 的 javascript 位于文件中,包括执行调用的内联 javascript 的页面文档 NORTH。结果 JSON 不是全局变量,范围阻止了它的使用。如果你真的需要一个全局变量,以便它可以与内联 JS 以及任何和所有包含的 js 文件一起使用,你可以这样做:

  (function(){
      var limitedScopeVariable = 25;
      window.globalScopeVariable = 30;
  })();

  $(function(){
       alert(globalScopeVariable); //works!
       alert(limitedScopeVariable); //fails!
  });

EDIT 2

编辑 2

As of jQuery 3.0, callback functions are different: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead

从 jQuery 3.0 开始,回调函数有所不同:从 jQuery 3.0 开始,jqXHR.success()、jqXHR.error() 和 jqXHR.complete() 回调方法被移除。您可以使用 jqXHR.done()、jqXHR.fail() 和 jqXHR.always() 代替

from the comments @mario-lurig

来自评论@mario-lurig

回答by Andy

the json data is passed to the callback function of $.getJSON. So this would work:

json 数据传递给 $.getJSON 的回调函数。所以这会起作用:

var jqxhr;

$.getJSON("example.json", function(data) {
  jqxhr = data;
});

// alert(jqxhr.property);
// caution: this won't work immediately on load, since the ajax call runs asynchronously and hasn't finished at that time

// it should be available at a later time, like a click event
$('a#something').click(function(){
     if(jqxhr){
          alert(jqxhr.property);
     }else{
          alert('getJSON not yet complete or failed');
     }
});

回答by Kumsal Obuz

I think this would be what you are looking for, you are trying to access the data returned from your call not the caller object itself. In your example, jqxhr is the object that handles the JSON call not the data. So,

我认为这将是您正在寻找的,您正在尝试访问从您的调用返回的数据而不是调用者对象本身。在您的示例中, jqxhr 是处理 JSON 调用而不是数据的对象。所以,

$.getJSON("example.json", function(data) {
  yourDATA = data;
})

//Use your data here
alert(yourDATA.aProperty);

The very first example on this pageis similar to what I explained.

此页面上的一个示例与我所解释的类似。