简体   繁体   English

从本地JSON文件加载后,javascript变量为“ null”或“ undefined”

[英]javascript variable is 'null' or 'undefined' after loading it from a local JSON file

I'm trying to create a javascript variable my_jason from the contents of a JSON file "gunsList.json" (both are stored within the same folder on my machine). 我正在尝试根据JSON文件“ gunsList.json”的内容创建一个JavaScript变量my_jason (两者均存储在我的计算机上的同一文件夹中)。

I seem to be having the same issue that the OP had in this post , which was resolved when he corrected his flawed JSON file. 我似乎遇到了OP在此帖子中遇到的相同问题,当他更正有缺陷的JSON文件时,该问题已得到解决。 Thinking I have the same issue, I ran my file through JSONLint (I'm assuming that's proper validation), and it came back clean. 以为我有同样的问题,我通过JSONLint运行了文件(我假设这是正确的验证),然后又恢复了正常。

Borrowing tips from this post , I tried using jQuery to get it done ( note : I'm using jQuery successfully in other parts of the existing code), as follows: 这篇文章中获得一些技巧,我尝试使用jQuery来完成它( 注意 :我在现有代码的其他部分成功地使用了jQuery),如下所示:

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

When I try the method above (eg, alert(my_json) ), my_json is undefined . 当我尝试上述方法(例如alert(my_json) )时, my_jsonundefined

Admittedly, I know very little about AJAX, but I also tried: 诚然,我对AJAX知之甚少,但我也尝试过:

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

In the case above, my_json is null . 在上述情况下, my_jsonnull

All my code that references the array within "gunsList.json" when I paste it in as a variable in my js file runs fine, but as a fledgling programmer, I'd be really excited about getting it to work with JSON. 当我将其粘贴为js文件中的变量时,所有引用“ gunsList.json”中的数组的代码都可以正常运行,但是作为一个刚起步的程序员,我非常高兴能够使其与JSON一起使用。

Here's why your original $.getJSON() code didn't work - the comments show the order of execution and the value of my_json at each step: 这就是您原来的$.getJSON()代码不起作用的原因-注释显示了执行顺序和每一步的my_json值:

var my_json;
// 1 - my_json is undefined
$.getJSON('gunList.json', function(json) {
    // 3 (!)
    my_json = json;
    // 4 - my_json now has the JSON data
});
// 2 - my_json is undefined (!)

As you can see, the function returns before the my_json value is set. 如您所见,该函数设置my_json之前返回。

So you tried to fix it by using the async: false option on a $.ajax() call instead. 因此,您尝试通过在$.ajax()调用上使用async: false选项来修复它。 But that is a very bad idea! 但这是一个非常糟糕的主意! Never use that option unless you have a very good reason for it: in many browsers, it will hang up not just your own site but all browser tabs and windows until your server returns the data. 除非你有一个很好的理由就不要使用该选项:在很多浏览器,直到你的服务器返回的数据就挂断不只是你自己的网站,但所有的浏览器标签和窗口。

Instead, let the $.ajax() or $.getJSON() call operate asynchronously, and do something with the data in the callback or in a function that you call from that callback. 而是让$.ajax()$.getJSON()调用异步操作,并对回调或从该回调调用的函数中的数据执行某些操作。 So, going back to your original $.getJSON() code, you can do this: 因此,回到原始的$.getJSON()代码,您可以执行以下操作:

$.getJSON( 'gunList.json', function( json ) {
    // Do stuff with JSON data here, or call a function here and
    // pass the data to it as an argument
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM