//获取css里ul的id属性 let uldom = document.getElementById("students"); //单独创建一个json文件,获取地址 let url = "data.json"; function main(){ fetch(url).then(respone=>{ return respone.json(); }).then(students=>{ let html = ``; for(let i=0, l=students.length; i<l; i++){ let name = students[i].name; let age = students[i].age; html += ` <li>姓名:${name},年龄:${age}</li> ` } uldom.innerHTML = html; }); } main();
结合await最终代码
let uldom = document.getElementById("students"); let url = "data.json"; async function main(){ let respone = await fetch(url); let students = await respone.json(); let html =``; for(let i=0, l=students.length; i<l; i++){ let name = students[i].name; let age = students[i].age; html += ` <li>姓名:${name},年龄:${age}</li> ` } uldom.innerHTML = html; } main();
data.json文件内容如下:
[ {"name":"张三","age":"3"}, {"name":"李万","age":"1"}, {"name":"王二","age":"4"}, {"name":"二狗","age":"3"}, {"name":"狗蛋","age":"5"}, {"name":"牛娃","age":"7"} ]
运行后结果是:
姓名:张三,年龄:3 姓名:李万,年龄:1 姓名:王二,年龄:4 姓名:二狗,年龄:3 姓名:狗蛋,年龄:5 姓名:牛娃,年龄:7
源码下载
下载地址:(jb51.net).rar
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。
您可能感兴趣的文章: