[英]How can I fetch from an JSON file and display some pictures
我正在尝试将提取的 JSON 数据中的多张图片显示到 DOM 中,我该如何高效地执行此任务? (只使用纯JS)
async function Data(){ const response = await fetch('https://gist.githubusercontent.com/whichbuffer/c835320d7dcf9899a22890b0a3589d88/raw/97f9bb3d4e0c9d558cc5184eb21a12831895dfa4/IMDB.json'); const data = await response.json(); console.log(data.Contents); for(let i=0;i<data.Contents.length;i++){ document.getElementById('Title').innerHTML +=("<br>" + data.Contents[i].Title + "<br>") document.getElementById('img').src += (data.Contents[i].Poster) } } Data().catch(error => { console.log("error!"); console.error(error); });
<img src="" id="img"> <p id="Title"></p>
这将为数组中的每个对象附加一个<li>
到<ul>
。
const list = document.getElementById("imglist") async function Data() { //Fetch the JSON const response = await fetch('https://gist.githubusercontent.com/whichbuffer/c835320d7dcf9899a22890b0a3589d88/raw/97f9bb3d4e0c9d558cc5184eb21a12831895dfa4/IMDB.json'); const data = await response.json(); //Loop over the fetched array for(let i = 0; i < data.Contents.length; i++){ //Create the `<li>` const li = document.createElement("li") //Create the `<p>` for the title and add it to the `<li>` const p = document.createElement("p") p.appendChild(document.createTextNode(data.Contents[i].Title)) li.appendChild(p) //Create the `<img>` for the poster and add it to the `<li>` const img = document.createElement("img") img.src = data.Contents[i].Poster li.appendChild(img) //Add the `<li>` to the list list.appendChild(li) } } Data().catch(error => { console.log("error!"); console.error(error); });
<ul id="imglist"></ul>
你能转储你的 XHR Request /Json Response 吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.