【发布时间】:2022-01-11 15:37:49
【问题描述】:
我遇到了问题;我有以下程序代码:
var xmlhttp = new XMLHttpRequest();
var url = "https://wjko5k6250.execute-api.us-east-2.amazonaws.com/motorcycle";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var allmot = JSON.parse(this.responseText);
console.log(allmot);
for(var i = 0, len = allmot.Items.length; i < len; i++)
{
id=allmot.Items[i].id
var url1 = "https://wjko5k6250.execute-api.us-east-2.amazonaws.com/motorcycle/"+id;
console.log(url1);
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
console.log(myArr);
document.getElementById("img").src = myArr.Item.image;
document.getElementById("brd").innerHTML = myArr.Item.brand;
}
};
xmlhttp.open("GET", url1, true);
xmlhttp.send();
}
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
allmot如下:
Items: Array (4)
0: {brand: 'Guzzi', id: '123456', image: 'moto_guzzi.jpg', date: '27/11/2021 '}
1: {brand: 'Bimota', id: '135623', image: 'bimota.jpg', date: '04/12/2021 '}
2: {brand: 'Ducati', id: '123789', image: 'b_desertx.jpg', date: ' 04/12/2021 '}
3: {brand: 'Benelli', id:' 146975 ', image:' benelli.jpg ', date: '27/11/2021'}
url1 返回(根据 for 循环):
https://wjko5k6250.execute-api.us-east-2.amazonaws.com/articles/123456
https://wjko5k6250.execute-api.us-east-2.amazonaws.com/articles/135623
https://wjko5k6250.execute-api.us-east-2.amazonaws.com/articles/123789
https://wjko5k6250.execute-api.us-east-2.amazonaws.com/articles/146975
到目前为止,一切似乎都很好。
问题出在myArr;我注意到它只返回最后一个元素的图像和品牌,所以它的 id 等于 146975。
因此,for 循环似乎存在问题。
谁能帮帮我?谢谢大家。
【问题讨论】:
-
您到底希望得到什么?我的意思是你一遍遍设置
#img的src和#brd的内容,最终的结果肯定是最后一次设置的值。 -
对于每一个我想获得的形象和品牌。它只对最后一个元素这样做
-
但是您只有一个图像和其他元素。
document.getElementById仅从 DOM 中找到具有传递的id的第一个元素。如果您有多个具有相同id的元素,那将不起作用。还要注意 pid 的回答。 -
我在@pid的回答下面回答了
标签: javascript loops for-loop