[英]XMLHttpRequest.status is “0” for AJAX Request
I am trying to create an app in Javascript that fetches data from a barcode database API ( http://upcdatabase.org/api ). 我正在尝试使用Javascript创建一个从条形码数据库API( http://upcdatabase.org/api )获取数据的应用程序。 When I make the AJAX requests, the GET requests are getting through to the API. 当我发出AJAX请求时,GET请求正在到达API。 I can see from the API's website how many requests I've made. 我可以从API的网站上看到我提出了多少个请求。
However, I am getting an XMLHttpRequest.status of "0" every time, on Firefox, Chrome, and Edge. 但是,在Firefox,Chrome和Edge上,每次都得到XMLHttpRequest.status为“ 0”。 I have a feeling I'm missing something since this is my first time doing this. 我有一种失落的感觉,因为这是我第一次这样做。
Here is the code I'm using: 这是我正在使用的代码:
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);
Thanks to anyone who can help! 感谢任何能提供帮助的人!
From the documentation : 从文档中 :
Before the request is complete, the value of
status
will be 0. 在请求完成之前,status
的值将为0。
The request isn't complete until readyState == 4
, so it's normal to see 0
if you log status
before that test is successful. 在readyState == 4
之前,请求没有完成,因此,如果在测试成功之前记录status
,则通常看到0
。 Try this: 尝试这个:
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.