2017-10-19 88 views
-1

我試圖在JavaScript中創建一個從條形碼數據庫API(http://upcdatabase.org/api)中獲取數據的應用程序。當我發出AJAX請求時,GET請求正在進入API。我可以從API的網站上看到我提出了多少請求。對於AJAX請求,XMLHttpRequest.status爲「0」

但是,我在Firefox,Chrome和Edge上每次都得到一個「0」的XMLHttpRequest.status。我有一種感覺,我錯過了一些東西,因爲這是我第一次這樣做。

這裏是我使用的代碼:

var upc = prompt("Enter UPC Code:"); 

var requestUrl = "https://api.upcdatabase.org/product/" + upc + 
    "/73114EC2F9C47240583DBF3AA190CB4C"; 

function httpGetAsync(theUrl) 
{ 
    var xmlHttp = new XMLHttpRequest(); 
    xmlHttp.onreadystatechange = function() { 
     if (xmlHttp.readyState == 4 && xmlHttp.status == 200) 
      alert(xmlHttp.responseText); 
    } 
    xmlHttp.open("GET", theUrl, true); 
    xmlHttp.send(); 
    alert(xmlHttp.status);  
} 

httpGetAsync(requestUrl); 

由於任何人誰可以幫助!

+1

該狀態爲0,因爲該調用還沒有返回,但... – Dekel

+0

你介意詳細說明嗎?我是否在代碼中過早詢問狀態? – Odocoileus

+0

@Oocoocoileus AJAX是異步的。在發生任何事情之前,你正在詢問狀態。把它放到'onreadystatechange'函數中。 – Barmar

回答

-1

documentation

請求完成以前,status的值爲0

請求是不完整的,直到readyState == 4,所以這是正常現象,如果0您在測試成功之前記錄status。試試這個:

function httpGetAsync(theUrl) 
{ 
    var xmlHttp = new XMLHttpRequest(); 
    xmlHttp.onreadystatechange = function() { 
     if (xmlHttp.readyState == 4) { 
      alert(xmlHttp.status); 
      if (xmlHttp.status == 200) { 
       alert(xmlHttp.responseText); 
      } 
     } 
    }; 
    xmlHttp.open("GET", theUrl, true); 
    xmlHttp.send(); 
}