关于前端:Promise请求

5次阅读

共计 525 个字符,预计需要花费 2 分钟才能阅读完成。

function ajax (url) {return new Promise((resolve, rejects) => {
    // 创立一个 XMLHttpRequest 对象去发送一个申请
    const xhr = new XMLHttpRequest()
    // 先设置一下 xhr 对象的申请形式是 GET,申请的地址就是参数传递的 url
    xhr.open('GET', url)
    // 设置返回的类型是 json,是 HTML5 的新个性
    // 咱们在申请之后拿到的是 json 对象,而不是字符串
    xhr.responseType = 'json'
    // html5 中提供的新事件, 申请实现之后(readyState 为 4)才会执行
    xhr.onload = () => {if(this.status === 200) {
        // 申请胜利将申请后果返回
        resolve(this.response)
      } else {
        // 申请失败,创立一个谬误对象,返回谬误文本
        rejects(new Error(this.statusText))
      }
    }
    // 开始执行异步申请
    xhr.send()})
}

ajax('/api/user.json').then((res) => {console.log(res)
}, (error) => {console.log(error)
})
正文完
 0