javascript的fetch,ajax

javascript的fetch,ajax

異步嵌套問題,fetch,ajax的對比
//異步嵌套問題  
//ajax  asynchronous javascript xmlhttprequest

function ajax(url){
    return new Promise(function(resolve,refused){
          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);
                    resolve(data);
                }
            }
            xmlHttp.send(null);
    });
}

let uldom=document.getElementById("students");
let url="http://localhost:3000/student.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();

//fetch
let url="http://localhost:3000/student.json";
        let uldom=document.getElementById("students");
        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();
看了兩個之間的對比,你更喜歡哪一個,也但願幫到你們
相關文章
相關標籤/搜索