我需要从JSON获取数组lenguajes []的语言并将其存储在“ custom_lenguajes”变量中,但我没有。
JSON输出:
{
- data:
[
- {
DT_RowId: "row_93",
idiomas: "Si",
site: "342800010",
lenguajes:
[
- {
id: "3",
code: "nl"
},
- {
id: "5",
code: "ja"
},
- {
id: "17",
code: "de"
},
- {
id: "19",
code: "en"
},
- {
id: "38",
code: "ru"
}
]
}
],
options:
{},
files: [ ]
}
JS代码:
var custom_lenguajes ="";
$(document).on('pageinit', '#page-1', function() {
// get lenguajes. START
$.getJSON( parser_origin + "/_country/spain/v134/lacarte.restaurants.front/alacarte/php/languages.front.php", { site: id_establecimiento()}, function(data){
for (var i=0, len=data.length; i < len; i++) {
console.log(data[i]);
}
data = data['data'];
data3 = data;
});
// I need create a variable that acummulate languages from JSON, this way: "nl,ja,de,en,ru"
$.each(data3, function(entryIndex, entry) {
$.each(this.lenguajes, function() {
alert(this.code); // don't show nothing. ONLY TEST
custom_lenguajes += this.code + "\,";
console.log(custom_lenguajes); //show "". ONLY TEST
});
});
// get lenguajes. END
...
您的帮助:
如果我使用console.log(data3); (在我的代码上)加载页面时,我可以在控制台镶边上看到一个空对象“ []”
之后,(当页面加载时),如果我在控制台chrome上写:data3 [0] .lenguajes [0] .code,它向我显示“ nl”。在chrome控制台上,它可以正常工作,但在我的代码上不行。
怎么了?我的循环或ASYNC是否有问题?
欢迎任何帮助!
谢谢!!
最佳答案
Javascript是异步的,这意味着它不会在尝试进入$.getJson()
循环之前等待ajax $.each()
函数完成。尝试将您的循环放入$.getJson()
函数中。
var custom_lenguajes ="";
$(document).on('pageinit', '#page-1', function() {
// get lenguajes. START
$.getJSON( parser_origin + "/_country/spain/v134/lacarte.restaurants.front/alacarte/php/languages.front.php", { site: id_establecimiento()}, function(data){
for (var i=0, len=data.length; i < len; i++) {
console.log(data[i]);
}
data = data['data'];
data3 = data;
$.each(data3, function(entryIndex, entry) {
$.each(this.lenguajes, function() {
alert(this.code); // don't show nothing. ONLY TEST
custom_lenguajes += this.code + "\,";
console.log(custom_lenguajes); //show "". ONLY TEST
});
});
});
});