我正在使用这个网站:https : //jsonplaceholder.typicode.com/users/作为使用 javascript 的 ajax 练习。
我正在尝试从多个 ID 中获取某个属性值。
让我们以电话为例。
如何遍历所有文件并获取每个 ID 和他的手机?
像这样:
id : 1 电话 : 123
id : 2 电话 : 124
我正在尝试使用,for...in
但我无法真正掌握它,而不是只循环使用其中的一个。
function callToServer(param) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
//if (this.readyState == (4) Done && this.status == (200) All good) {
if (this.readyState == 4 && this.status == 200) {
res = JSON.parse(this.responseText);
for (var key in res) {
demo.innerHTML += `${key} : ${res[key]}<br>`;
}
}
}
// notice that I used "9" after to loop only through 1 :)
xhttp.open("GET", "https://jsonplaceholder.typicode.com/users/9", true);
xhttp.send();
}
循环遍历数组并获取每个元素的id
和phone
属性。您可以使用forEach()
它而不是for
循环。请参阅为什么使用“for...in”进行数组迭代是个坏主意?
function callToServer() {
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let html = '';
let res = JSON.parse(this.responseText);
res.forEach(user => demo.innerHTML +=
html += `id ${user.id}: phone ${user.phone}<br>`;
)
demo.innerHTML = html;
}
}
xhttp.open("GET", "https://jsonplaceholder.typicode.com/users", true);
xhttp.send();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句