fetch結合(async函數來使用)
<ul id="students">
</ul>
ajax請求
function ajax(url){
let xmlHttp=new XMLHttpRequest();
xmlHttp.open("get",url,true);
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4&&xmlHttp.status==200){
let data= JSON.parse(xmlHttp.responseText);
console.log(data);
}
}
xmlHttp.send(null);
}
ajax(url);
let uldom=document.getElementById("students");
let url="http://192.168.0.46:8000/student.json";
對於使用fetch能夠方便不少,這就是下面要使用的fetch的代碼,先熟悉瞭解下:
/*fetch(url).then(respone=>{
//return respone.text();
return respone.json();
}).then(data=>{
console.log(data);
})*/
使用fetch
//獲取css裏ul的id屬性
let uldom=document.getElementById("students");
//單首創建一個json文件,獲取地址
let url="http://192.168.0.46:8000/student.json";
function main(){
fetch(url).then(respone=>{
//return respone.text();
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();
最終代碼
let uldom=document.getElementById("students");
let url="http://192.168.0.46:8000/student.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();
這是個人json文件裏的代碼:
[
{"name":"ss","age":"3"},
{"name":"aa","age":"1"},
{"name":"qq","age":"4"},
{"name":"zz","age":"3"},
{"name":"xx","age":"5"},
{"name":"cc","age":"7"}
]
最後結果:
姓名ss,年齡3
姓名aa,年齡1
姓名qq,年齡4
姓名zz,年齡3
姓名xx,年齡5
姓名cc,年齡7