如何捕获涉及XmlHttpRequest的错误?

Hit*_*iss 6 javascript ajax

当我通过XMLHttpRequest将数据发送到服务器时,我想借助TRY {} CATCH(){}捕获所有错误。

如何接收所有错误,例如net::ERR_INTERNET_DISCONNECTED等等?

Fra*_*rmu 5

尝试捕获对我不起作用。我个人最终测试了 response == "" 和 status == 0。

        var req = new XMLHttpRequest();
        req.open("post", VALIDATE_URL, true);
        req.onreadystatechange = function receiveResponse() {

            if (this.readyState == 4) {
                if (this.status == 200) {
                    console.log("We got a response : " + this.response);
                } else if (!isValid(this.response) && this.status == 0) {
                    console.log("The computer appears to be offline.");
                }
            }
        };
        req.send(payload);
        req = null;
Run Code Online (Sandbox Code Playgroud)


小智 -2

参考这个,

function createXMLHttpRequestObject()
{
  // xmlHttp will store the reference to the XMLHttpRequest object
  var xmlHttp;
  // try to instantiate the native XMLHttpRequest object
  try
  {
    // create an XMLHttpRequest object
    xmlHttp = new XMLHttpRequest();
  }
  catch(e)
  {
        try
    {
      xmlHttp = new ActiveXObject("Microsoft.XMLHttp");
    }
    catch(e) { }
  }
  // return the created object or display an error message
  if (!xmlHttp)
    alert("Error creating the XMLHttpRequest object.");
  else 
    return xmlHttp;
}
Run Code Online (Sandbox Code Playgroud)