[英]Add values from JSON output on JavaScript variable, fail on Loop or Async?
我需要从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
...
您的帮助:
怎么了? 我的循环或ASYNC是否有问题?
欢迎任何帮助! 谢谢!!
Javascript是异步的,这意味着它不会在尝试进入$.each()
循环之前等待ajax $.getJson()
函数完成。 尝试将您的循环放入$.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
});
});
});
});
谢谢您的帮助。
是的,您的评论方向正确(在$ .getJSON内部循环),现在可以正常工作! 起作用的最终代码:
$.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: "nl,ja,de,en,ru"
$.each(data3, function(entryIndex, entry) {
$.each(this.lenguajes, function() {
//alert(this.code); // ONLY TEST
custom_lenguajes += this.code + "\,";
//console.log(custom_lenguajes); //ONLY TEST
});
});
});// end $.getJSON
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.