2017-04-07 127 views
1

我有一個劇本,我想從一個端點獲取一些JSON數據,但我得到一個錯誤,這是我的腳本:E6 Ajax請求不工作

function httpGet(url) { 
    return new Promise(
     function (resolve, reject) { 
      var request = new XMLHttpRequest(); 
      request.onreadystatechange = function() { 
       if (this.status === 200) { 
        // Success 
        resolve(this.response); 
       } else { 
        // Something went wrong (404 etc.) 
        reject(new Error(this.statusText)); 
       } 
      } 
      request.onerror = function() { 
       reject(new Error(
        'XMLHttpRequest Error: '+this.statusText)); 
      }; 
      request.open('GET', url); 
      request.send(); 
     }); 
} 

var url = 'https://api.jsonPlaceholder.com'; 

httpGet(url) 
    .then(JSON.parse) 
    .then((r) => { 
    console.log(r); 
    }).catch(function(error) { 
    console.log(error); 
    }); 

然後,在控制檯它拋出一個錯誤:

Error at XMLHttpRequest.request.onreadystatechange (app.js:11) at app.js:18 at Promise() at httpGet (app.js:2) at app.js:25

+2

只是好奇...爲什麼不使用['Fetch API'](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)? – Andreas

+0

@Andreas:可能想要支持IE? –

+0

除了api url以外,似乎對我來說運行良好。你使用的是什麼瀏覽器? – epascarello

回答

1

你不能只檢查status,你必須檢查readyState == 4,然後才能決定什麼發生了:

function httpGet(url) { 
    return new Promise(
     function (resolve, reject) { 
      var request = new XMLHttpRequest(); 
      request.onreadystatechange = function() { 
       if (this.readyState === 4) {       // *** 
        if (this.status === 200) { 
         // Success 
         resolve(this.response); 
        } else { 
         // Something went wrong (404 etc.) 
         reject(new Error(this.statusText)); 
        } 
       }              // *** 
      } 
      request.onerror = function() { 
       reject(new Error(
        'XMLHttpRequest Error: '+this.statusText)); 
      }; 
      request.open('GET', url); 
      request.send(); 
     }); 
} 

The spec表示在請求完成之前訪問this.response應該返回一個空字符串,但對於我使用Chrome v57的用戶,這樣做會導致您引用的錯誤。添加readyState檢查修復它。

+1

雖然這不會引發錯誤,對嗎?難道它不是早點觸發Promise'catch'嗎? – CodingIntrigue

+0

@CodingIntrigue:這是一個很好的觀點,它對我非常激動,我不記得引用錯誤。所以我想知道'this.response'是否正在拋出,但[規範](https://xhr.spec.whatwg.org/#the-response-attribute)如果您訪問得太早,不會說出它。編輯:啊,鉻儘管規範拋出... –

+0

現在這個作品,我可以獲取數據,與您的代碼 – Leff