手写 JS 原生 Fetch API ajax请求数据并展现

19 阅读1分钟
//首先是创建方法并调用
async function getData(){
    // 首先是获取可用的api网站地址,这个是网上找的,默认是get请求,并且使用await,
    // 因为是异步请求,所以得等数据完成请求过来
    const res = await fetch('https://jsonplaceholder.typicode.com/posts')

    //就获取到的数据赋值给data1这个属性
    const data1 = await res.json()

    // 打印获取到的信息
    console.log(data1);

    // 监听html中id为root的容器
    const root = document.querySelector('#root')

    // 创建ul
    const ul = document.createElement('ul')

    // 遍历获取到的数据,也就是data2
    data1.forEach(data2 => {
        // 创建li标签
        const li = document.createElement('li')
        // 创建a标签,用来展示遍历得到的挑剔
        const anchor = document.createElement('a')
        // 通过创建a来展示数据的标题,以数据文章标题做展示
        anchor.appendChild(document.createTextNode(data2.title))
        //通过href形式实现点击标题形式跳转展示具体内容,已数据的id作为索引
        anchor.setAttribute('href',`https://jsonplaceholder.typicode.com/posts/${data2.id}`)

        li.appendChild(anchor)

        ul.appendChild(li)

    });
    root.appendChild(ul)
}
getData()