我在从 json 物件获取不同的 ID 时遇到问题。我得到的是最后一项的 id。
这是函式:
var xmlhttp = new XMLHttpRequest();
var url = "https://wjko5u2865.execute-api.us-east-2.amazonaws.com/articles";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var allart = JSON.parse(this.responseText);
for(let i = 0; i < allart.Items.length; i )
{
document.getElementById("id").innerHTML = allart.Items[i].id;
}
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
这是我得到的json阵列:
{
"Items":[{
"marca":"Guzzi",
"titolo":"Moto Guzzi V100 Mandello, la regina di EICMA 2021",
"id":"123456",
"immagine":"moto_guzzi_v100_mandello.jpg",
"data":"27/11/2021"
},
{
"marca":"Bimota","titolo":"Bimota: arriverà un'adventure su base Tesi",
"id":"135623",
"immagine":"bimota-_arrivera_unadventure_su_base_tesi.jpg",
"data":"04/12/2021"
},
{
"marca":"Ducati",
"titolo":"Ducati, la DesertX sarà svelata a Dubai il 9 dicembre",
"id":"123789",
"immagine":"b_desertx-dwp2022-2-uc336332-high.jpg",
"data":"04/12/2021"
},
{"marca":"Benelli",
"titolo":"EICMA 2021, Benelli \"sforna\" le moto più attese",
"id":"146975",
"immagine":"benelli_2.jpg",
"data":"27/11/2021"
}
],
"Count":4,"ScannedCount":4}
提前感谢大家
uj5u.com热心网友回复:
您代码中的具体错误是这一行:
document.getElementById("id").innerHTML = allart.Items[i].id;
在“=”之前需要一个“ ”来向innerHTML 添加更多的字符串/id。
document.getElementById("id").innerHTML = "<br/>" allart.Items[i].id;
我做了一个替代解决方案,我使用Array.prototype.map()创建一个包含所有 id 的阵列,然后使用Array.prototype.join()创建一个包含所有 id 的字符串。
var xmlhttp = new XMLHttpRequest();
var url = "data:application/json;base64,ewogICJJdGVtcyI6W3sKICAgICJtYXJjYSI6Ikd1enppIiwKICAgICJ0aXRvbG8iOiJNb3RvIEd1enppIFYxMDAgTWFuZGVsbG8sIGxhIHJlZ2luYSBkaSBFSUNNQSAyMDIxIiwKICAgICJpZCI6IjEyMzQ1NiIsCiAgICAiaW1tYWdpbmUiOiJtb3RvX2d1enppX3YxMDBfbWFuZGVsbG8uanBnIiwKICAgICJkYXRhIjoiMjcvMTEvMjAyMSIKICAgIH0sCiAgICB7CiAgICAibWFyY2EiOiJCaW1vdGEiLCJ0aXRvbG8iOiJCaW1vdGE6IGFycml2ZXLgIHVuJ2FkdmVudHVyZSBzdSBiYXNlIFRlc2kiLAogICAgImlkIjoiMTM1NjIzIiwKICAgICJpbW1hZ2luZSI6ImJpbW90YS1fYXJyaXZlcmFfdW5hZHZlbnR1cmVfc3VfYmFzZV90ZXNpLmpwZyIsCiAgICAiZGF0YSI6IjA0LzEyLzIwMjEiCiAgICB9LAogICAgewogICAgIm1hcmNhIjoiRHVjYXRpIiwKICAgICJ0aXRvbG8iOiJEdWNhdGksIGxhIERlc2VydFggc2Fy4CBzdmVsYXRhIGEgRHViYWkgaWwgOSBkaWNlbWJyZSIsCiAgICAiaWQiOiIxMjM3ODkiLAogICAgImltbWFnaW5lIjoiYl9kZXNlcnR4LWR3cDIwMjItMi11YzMzNjMzMi1oaWdoLmpwZyIsCiAgICAiZGF0YSI6IjA0LzEyLzIwMjEiCiAgICB9LAogICAgeyJtYXJjYSI6IkJlbmVsbGkiLAogICAgInRpdG9sbyI6IkVJQ01BIDIwMjEsIEJlbmVsbGkgXCJzZm9ybmFcIiBsZSBtb3RvIHBp SBhdHRlc2UiLAogICAgImlkIjoiMTQ2OTc1IiwKICAgICJpbW1hZ2luZSI6ImJlbmVsbGlfMi5qcGciLAogICAgImRhdGEiOiIyNy8xMS8yMDIxIgogICAgfQogICAgXSwKICAgICJDb3VudCI6NCwiU2Nhbm5lZENvdW50Ijo0fQo=";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let allart = JSON.parse(this.responseText);
let ids = allart.Items.map(item => item.id).join('<br/>');
document.getElementById("id").innerHTML = ids;
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
<div id="id"></div>
0 评论