4

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();
看了两个之间的对比,你更喜欢哪个,也希望帮到大家

姜筱妍
269 声望10 粉丝

君生我未生,我生君已老。