简体   繁体   English

在全局变量上使用$ .getJSON似乎不起作用

[英]Using $.getJSON on a global variable doesn't seem to work

I'm extremely new to Javascript and jQuery and I'm not quite understanding why the following code doesn't work 我对Javascript和jQuery非常陌生,我不太了解以下代码为何不起作用

var collectibleCards = [];

$(document).ready(function () {
    $.getJSON('AllSets.json', function (json) {
        $.each(json, function(sets, cards) {
            $.each(cards, function(element, card) {
                if(card['collectible'] && card['type'] !== "Hero") {
                    collectibleCards.push(new Card(card));
                }
            });
        });
    });
});

console.log(collectibleCards.length); // prints 0

Why does collectibleCards not get any elements added? 为什么collectibleCards没有添加任何元素? I've even tried just pushing numbers and still get nothing added to the array. 我什至尝试过仅推送数字,仍然没有将任何内容添加到数组中。

It's because getJSON is async operation and result of the callback will appear after some time, when browser get response from the server (or, in your case, from a json file). 这是因为getJSON是异步操作,并且当浏览器从服务器(或您的情况下,从json文件)获得响应时,回调的结果将在一段时间后出现。 So lets see: 因此,让我们看看:

// You create a variable
var collectibleCards = [];

// You start your ajax request by doing getJSON
$.getJson('AllSets.json', function () { // This code will evaluate AFTER browser get response from the file });

// You logged your variable and it still an emtpy array because ajax doesn't get a response yet
console.log(collectibleCards.length); // prints 0

You are trying to access the variable before its getting updated in success callback of getJSON, thats why you are getting it of length 0, If you want to access it outside of callback then use $.ajax and make it synchronous call else manipulate on collectibleCards in callback function itself not outside. 您正在尝试访问变量,然后在getJSON的成功回调中对其进行更新,这就是为什么要获取长度为0的原因,如果要在回调之外访问它,请使用$ .ajax并使其同步调用,否则对collectibleCards进行操作在回调函数本身不在外面。

var collectibleCards = [];

$(document).ready(function () {
    $.getJSON('AllSets.json', function (json) {
        $.each(json, function(sets, cards) {
            $.each(cards, function(element, card) {
                if(card['collectible'] && card['type'] !== "Hero") {
                    collectibleCards.push(new Card(card));
                }
            });
        });
       console.log(collectibleCards.length); // print correct length
    });
});

Also see Calling Ajax and returning response 另请参见调用Ajax并返回响应

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

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