JavaScript HTTP请求失败

时间:2016-08-10 18:53:26

标签: javascript jqxhr

任何人都可以看看下面的代码帮我弄清楚我做错了什么?我收到此错误

  

错误XMLHttpRequest {readyState:1,timeout:0,withCredentials:   false,upload:XMLHttpRequestUpload,responseURL:“”...}

当我试图向NASA图像galary请求获取图像时..

HTML:

<img id="map" src="" alt="image from NASA"> 

JS:

var get = function(url){
    return new Promise(function(resolve,reject){
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4 && xhr.status == 200){
                var result = xhr.responseText;
                result = JSON.parse(result);
                resolve(result);
            }else {
                reject(xhr);
            }
        }
        xhr.open("GET",url,true);
        xhr.send(null);
    })
}

get('https://api.nasa.gov/planetary/apod?api_key=NNKOjkoul8n1CH18TWA9gwngW1s1SmjESPjNoUFo'
)
.then(function(response){
    console.log("success",response);
    document.getElementById('map').src = response.url;
})
.catch(function(err){
    console.log('error',err)
})

1 个答案:

答案 0 :(得分:1)

你的其他陈述在错误的地方

ajax请求通过这些不同的状态

State  Description
0      The request is not initialized
1      The request has been set up
2      The request has been sent
3      The request is in process
4      The request is complete

readyState事件将在这些状态发生变化时触发,这就是为什么我们检查第四个状态是触发回调的状态,当请求完成时,我们有返回的数据。

您正在使用会在1上触发的else语句,或者除了4之外的任何状态,但1是第一个readyState,当您首次设置请求时,必须等到它达到第四个readyState

var get = function(url){
    return new Promise(function(resolve,reject){
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4) {
                if (xhr.status == 200) {
                    var result = xhr.responseText;
                    result = JSON.parse(result);
                    resolve(result);
                }else {
                    reject(xhr);
                }
            }
        }
        xhr.open("GET",url,true);
        xhr.send(null);
    })
}

FIDDLE