有一個在我的Firefox WebExtensions的內容腳本一個XMLHttpRequest添加上。問:爲什麼這個請求的狀態總是0?XMLHttpRequest的狀態0在
這是JavaScript代碼發出請求:
var query = "http://api.wolframalpha.com/v2/query?appid=[MY-APP-ID]&includepodid=Comparison&scanner=Unit&format=plaintext&input=1%20lm";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
console.log("onreadystatechange");
console.log(this);
if (this.readyState == 4 && this.status == 200)
{
onSuccess(this.responseText);
}
};
xhttp.open("GET", query, true);
xhttp.send();
如果我打印出每個onreadystatechange的呼叫請求的結果,我得到:
XMLHttpRequest { onreadystatechange: makeWolframRequest/xhttp.onreadystatechange(),
readyState: 1, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload,
responseURL: "", status: 0, statusText: "", responseType: "", response: "" }
XMLHttpRequest { onreadystatechange: makeWolframRequest/xhttp.onreadystatechange(),
readyState: 2, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload,
responseURL: "", status: 0, statusText: "", responseType: "", response: "" }
XMLHttpRequest { onreadystatechange: makeWolframRequest/xhttp.onreadystatechange(),
readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload,
responseURL: "", status: 0, statusText: "", responseType: "", response: "" }
事情我檢查:
- 內容腳本應該能夠根據WebExtensions documentation進行跨域請求。
- 發出請求,以「https://api.wolframalpha.com/」,而不是「http://api.wolframalpha.com/」。
的'readystatechange'事件激發每當readyState的變化,前三個發生在服務器響應之前,你不能有一個狀態碼,你有一個響應之前,這就是爲什麼它是'0'前三次,這也是我們檢查'readystate'是否爲'4'的原因,因爲這表明得到了響應。這個問題可能不是三個第一個「readystatechange」調用的狀態代碼,而是別的。 – adeneo
在我的實驗中,日誌的readystate值是1,2和4.我同意狀態0對於狀態1和狀態2(在前兩個日誌中)是有意義的,但是狀態爲0的狀態爲4是我擔心的原因。 – Gladclef
如果ready狀態爲「4」時狀態仍爲「0」,通常表示還有其他問題。我沒有應用ID,也無法測試,但我猜這是一個CORS錯誤。您是否爲腳本設置了正確的權限,您不能通過請求正確的權限來允許跨域調用? – adeneo