如何从 JavaScript 获取 HTTP 状态
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3298748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get HTTP status from JavaScript
提问by d.garanzha
How to get HTTP status code of another site with JavaScript?
如何使用 JavaScript 获取另一个站点的 HTTP 状态代码?
采纳答案by Anders
I assume JavaScript, with JQuery, which simplifies AJAX requests alot, like this.
我假设 JavaScript 和 JQuery 一起简化了 AJAX 请求,就像这样。
$.ajax({
url: 'url',
type: 'GET',
complete: function(transport) {
doing whatever..
}
});
回答by Ahmed Aman
Try the following piece of javascript code:
试试下面这段 javascript 代码:
function getReq() {
var req = false;
if(window.XMLHttpRequest) {
try {
req = new XMLHttpRequest();
} catch(e) {
req = false;
}
} else if(window.ActiveXObject) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
req = false;
}
}
if (! req) {
alert("Your browser does not support XMLHttpRequest.");
}
return req;
}
var req = getReq();
try {
req.open("GET", 'http://www.example.com', false);
req.send("");
} catch (e) {
success = false;
error_msg = "Error: " + e;
}
alert(req.status);
回答by Awin
You will have to use XMLHTTPRequest for getting the HTTP status code. This can be done by making a HEAD request to the server for the required url. Create an XMLHTTPRequest object - xhr, and do the following
您必须使用 XMLHTTPRequest 来获取 HTTP 状态代码。这可以通过向服务器发出所需 url 的 HEAD 请求来完成。创建一个 XMLHTTPRequest 对象 - xhr,并执行以下操作
xhr.open("HEAD", <url>,true);
xhr.onreadystatechange=function() {
alert("HTTP Status Code:"+xhr.status)
}
xhr.send(null);
See herefor more details.
请参阅此处了解更多详情。
回答by Ollie Edwards
You can't do this with AJAX directly because of the same origin policy.
由于同源策略,您不能直接使用 AJAX 执行此操作。
You'd have to set up a proxy service on your server then make ajax calls to that with the address you want to check. From your server proxy you can use cURL or whatver tool you like to check the status code and return it to the client.
您必须在服务器上设置代理服务,然后使用要检查的地址对它进行 ajax 调用。从您的服务器代理,您可以使用 cURL 或任何您喜欢的工具来检查状态代码并将其返回给客户端。

