简体   繁体   English

如何从JavaScript获取HTTP状态

[英]How to get HTTP status from JavaScript

如何使用JavaScript获取其他网站的HTTP状态代码?

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);

You will have to use XMLHTTPRequest for getting the HTTP status code. 您必须使用XMLHTTPRequest来获取HTTP状态代码。 This can be done by making a HEAD request to the server for the required url. 这可以通过向服务器发出针对所需URL的HEAD请求来完成。 Create an XMLHTTPRequest object - xhr, and do the following 创建XMLHTTPRequest对象 - xhr,并执行以下操作

 xhr.open("HEAD", <url>,true);
 xhr.onreadystatechange=function() {
     alert("HTTP Status Code:"+xhr.status)
 }
 xhr.send(null);

See here for more details. 有关详细信息,请参见此处

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. 您必须在服务器上设置代理服务,然后使用您要检查的地址对其进行ajax调用。 From your server proxy you can use cURL or whatver tool you like to check the status code and return it to the client. 从您的服务器代理,您可以使用cURL或您喜欢的任何工具来检查状态代码并将其返回给客户端。

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..
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM