【发布时间】:2019-05-20 09:48:42
【问题描述】:
我编写了一些代码来通过 AJAX 使用 JSON。而且它没有按照我想要的方式工作 - 我的网站上有一些未定义的东西。
我试过了:
let productsList = document.querySelector('.product-list-container__list-line');
function getDataAssync() {
let httpReq = new XMLHttpRequest();
let template = '';
httpReq.open('GET', 'https://raw.githubusercontent.com/maksymilianMroz/items-for-ajax/master/items.json');
httpReq.addEventListener('readystatechange', function () {
if (this.readyState == 4 && this.status == 200) {
let content = this.responseText;
content = JSON.parse(content);
let klucze = Object.keys(content)
console.log(content);
console.log(klucze);
klucze.forEach(element => {
template +=
`<div class="product-list-container__list-item">
<img src="${element.gallery}">
<h4>${element.name}</h4>
</div>`
});
if(template != '') {
productsList.innerHTML = template;
}
}
});
httpReq.send();
}
productsList.addEventListener('click', getDataAssync);
但是我的操作的输出是一个 div(我想要 JSON 中的所有对象),src=undefinend(我想要 JSON 中的画廊数组中的第一个 img)和 name=undefinend(我想要 JSON 中的对象中的名称)
我希望将 JSON 中的所有项目(不是单个项目)放入我网站上的 div 中 - 将名称(来自 JSON)和项目数组中的第一个 img 称为画廊(也来自 JSON)作为 src 到我的 img。
【问题讨论】:
-
JSON 是什么样的?
标签: javascript json ajax xmlhttprequest