手写ajax

image

// const xhr = new XMLHttpRequest()
    // //true支持异步
    // xhr.open('get', '/work1/javascript/ajax/ziyuan.json', true)
    // xhr.onreadystatechange = function() {
    //   if(xhr.readyState === 4) {
    //     if(xhr.status === 200) {
    //       console.log(JSON.parse(xhr.responseText))
    //     }
    //   }
    // }
    // xhr.send(null)
    function ajax(url) {
      const p =  new Promise( (resolve, reject) => {
        const xhr = new XMLHttpRequest() 
        xhr.open('get', url, true)
        xhr.onreadystatechange = function() {
          if(xhr.readyState === 4) {
            if(xhr.status === 200) {
              resolve(xhr.responseText)
            }else if(xhr.status === 404) {
              reject('404 server ')
            }
          }
        }
        xhr.send(null)
      })
      return p
    }
    ajax('/work1/javascript/ajax/ziyuan.json').then( data => {
      console.log(data)
    }).catch( err => {
      cosole.log(err)
    })
posted @ 2021-04-10 20:40  嘿!那个姑娘  阅读(47)  评论(0编辑  收藏  举报