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

时间:2015-05-09 21:40:39

标签: javascript jquery

我对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

为什么collectibleCards没有添加任何元素?我甚至尝试过推送数字,但仍然没有添加任何数据。

2 个答案:

答案 0 :(得分:3)

这是因为getJSON是异步操作,并且当浏览器从服务器(或者在您的情况下,从json文件)获得响应时,回调的结果将在一段时间后出现。 所以让我们看看:

// 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

答案 1 :(得分:0)

你试图在变量成功回调getJSON之前访问该变量,这就是为什么你得到它的长度为0,如果你想在回调之外访问它,那么使用$ .ajax并使它同步调用else在回调函数本身而不是在外面操纵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
    });
});

另见 Calling Ajax and returning response

相关问题