咱們昨天學習了async和await,知道他是爲了解決瀏覽器異步獲取的的!可是咱們用fetch api的話方法會更加的簡單html
function ajax(url){ return new Promise(function(reslove,reject){ 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); reslove(data); } } xmlHttp.send(null); }) } let uldom=document.getElementById("students"); let url="http://192.168.0.57:8000/students.json"; async function main(){ let data=await ajax(url); let students=data; 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();
咱們須要建立Promise函數來進行操做,若是咱們用fetch解決的話,會更加的方便!ajax
let uldom=document.getElementById("students"); let url="http://192.168.0.57:8000/students.json"; function main(){ fetch(url).then(respone=>{ return respone.json(); }).then(data=>{ let students=data; 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();
不用建立Promise,直接調用then()是否是比上邊更加的簡單!json
let uldom=document.getElementById("students"); let url="http://192.168.0.57:8000/students.json"; async function main(){ let respone = await fetch(url); let student = 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()
感受是否是很簡單!比上一種方法更加的簡單。api