fetch连系(async函数来运用)

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
    原文作者:师妹儿
    原文地址: https://segmentfault.com/a/1190000010280423
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞