[英]Access array values inside json object
i get this with use of xmlhttprequest then i json.parse it and then for loop through the "resonse" to populate a list.我通过使用 xmlhttprequest 然后我 json.parse 它得到这个然后通过“resonse”循环填充列表。
You can see in the next picture how the array in "response" looks when i click on "[0...99].您可以在下一张图片中看到当我单击“[0...99] 时“响应”中的数组的外观。
My problem is that the for loop doesnt populate the list tag in html, but when i try to write only for albania then it works.我的问题是 for 循环没有填充 html 中的列表标记,但是当我尝试只为阿尔巴尼亚写时它就起作用了。 I need help with only javascript and not jQuery. you can see my code here:我只需要 javascript 而不是 jQuery 的帮助。你可以在这里看到我的代码:
The HTML part: HTML部分:
<section class="country">
<h3 id="countries"><br /></h3>
<nav id="countries2">
<ul id="countrylist"></ul>
</nav>
</section>
Here is javascript part:这是 javascript 部分:
var jsonData = JSON.parse(xhr.responseText);
document.getElementById("countrylist").innerHTML = "";
for (var i = 0; i < jsonData.response[i].length; i++) {
document.getElementById("countrylist").innerHTML += "<li id='" + jsonData.response[i].code + "'>" + jsonData.response[i].name + "</li>";
}
Here is the javascript part that works without foor loop:这是没有 foor 循环的 javascript 部分:
document.getElementById("countrylist").innerHTML += "<li id='" + jsonData.response[0].code + "'>" + jsonData.response[0].name + "</li>";
Your for loop is ending early.您的 for 循环提前结束。 Your condition is wrong.你的条件不对。
What you have你有什么
for (var i = 0; i < jsonData.response[i].length; i++) {
What you should have你应该有什么
for (var i = 0; i < jsonData.response.length; i++) {
Your condition is against the length of the first element and is ending immediately.您的条件与第一个元素的长度相反,并且立即结束。
Looking at your for loop condition:查看您的 for 循环条件:
for (var i = 0; i < jsonData.response[i].length; i++) {
jsonData.response[i].length
is not the length of the array, but the length of one array element (in this case it is 1
). jsonData.response[i].length
不是数组的长度,而是一个数组元素的长度(在本例中为1
)。 So your loop is only executing once.所以你的循环只执行一次。
You want instead to loop over all the array, like so:您想要遍历所有数组,如下所示:
for (var i = 0; i < jsonData.response.length; i++) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.