[英]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.