且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将json从文件加载到对象中

更新时间:2022-06-02 22:02:20

我认为你太复杂了:)

 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"); });

getJSON函数自动将您的响应转换为适当的JSON对象。无需解析。

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

您提到您在整个地方使用此数据,因此您必须等待ajax调用完成才能访问数据。这意味着将整个应用程序包装在 getJSON 回调中。或者使用自定义事件来确定如下:

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 getJSON callback. Or using a custom event to determine like so:

 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);
       }          
 });

编辑

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

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:

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

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

编辑2


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

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

来自评论@ mario-lurig

from the comments @mario-lurig