【问题标题】:Why does not if statement check the status of the http request below?为什么 if 语句不检查下面的 http 请求的状态?
【发布时间】:2020-10-30 17:36:36
【问题描述】:

发送http请求后我检查状态是否为200然后resolve() 但是 if 语句似乎不起作用

 function getMelumat(){
        let promise = new Promise((resolve,reject)=>{
        let xhr = new XMLHttpRequest();
        xhr.open("GET",'https://jsonplaceholder.typicode.com/posts');
        xhr.send()
        xhr.onload = ()=>{
            if ( this.status == 200){
                resolve(this.response)
            }
            else{
               throw "AN ERROR OCCURED"
           }
          }

        })

     return promise

    }


            getMelumat().then(data=>{
                return JSON.parse(data)
            }).then(data=>{
                console.log(data)
            })

【问题讨论】:

  • console.log(this) 你会发现问题。
  • 是的,这都是关于“this”所指的我使用了 function(){} 语法并且它有效

标签: javascript http xmlhttprequest


【解决方案1】:

检查状态是否为 200 是不够的;您还需要检查this.readyState

标头(带有状态)已经可以在this.readyState == 2 获得,但整个响应要到this.readyState == 4 才能完成。

【讨论】:

    猜你喜欢
    • 2019-11-23
    • 2020-04-11
    • 2021-12-03
    • 2014-12-27
    • 1970-01-01
    • 2018-11-15
    • 2013-10-03
    • 1970-01-01
    相关资源
    最近更新 更多