簡體   English   中英

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

[英]Using $.getJSON on a global variable doesn't seem to 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

為什么collectibleCards沒有添加任何元素? 我什至嘗試過僅推送數字,仍然沒有將任何內容添加到數組中。

這是因為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

您正在嘗試訪問變量,然后在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
    });
});

另請參見調用Ajax並返回響應

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM