我有一个ajax有时会返回数据
{
"results": [{
"symbol": "AppConomy",
"Name": null,
"PriceSales": null
}]
}
对于我的forEach函数上面的工作正常,但是当返回相同的数据时
{
"results": {
"symbol": "AppConomy",
"Name": null,
"PriceSales": null
}
}
我的forEach函数不起作用
$.get(url, function(data){
var x =data['results'];
x.forEach(function logArrayElements(element, index, array) {
$(self).append('<button class="tag-format" title="'+array[index].Name+'" style="color:#fff;background-color:rgb(0,151,216);border:1px solid;border-radius:10px;"> '+ array[index].symbol +" - "+ array[index].PriceSales +' </button>');
});
});
那是因为您的JSON不是数组。您可以使用Array.isArray()轻松地事先进行检查。如果要getJSON
检索的数据实际上是JSON,则也应该使用。
$.getJSON(url, function(data) {
var x = data.results;
if(Array.isArray(x)) {
x.forEach(function logArrayElements(element, index, array) {
$(self).append('<button class="tag-format" title="' + array[index].Name + '" style="color:#fff;background-color:rgb(0,151,216);border:1px solid;border-radius:10px;"> ' + array[index].symbol + " - " + array[index].PriceSales + ' </button>');
});
} else {
$(self).append('<button class="tag-format" title="' + x.Name + '" style="color:#fff;background-color:rgb(0,151,216);border:1px solid;border-radius:10px;"> ' + x.symbol + " - " + x.PriceSales + ' </button>');
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句