当我通过XMLHttpRequest发送数据到服务器时,我想在TRY {} CATCH(){}的帮助下捕获所有错误。如何捕获涉及XmlHttpRequest的错误?
如何接收所有错误,例如net::ERR_INTERNET_DISCONNECTED
等?
当我通过XMLHttpRequest发送数据到服务器时,我想在TRY {} CATCH(){}的帮助下捕获所有错误。如何捕获涉及XmlHttpRequest的错误?
如何接收所有错误,例如net::ERR_INTERNET_DISCONNECTED
等?
转寄此,
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;
}
非常感谢。我要去试试) – 2014-11-05 12:14:58
你应该把所有你认为会导致try块异常的语句。之后,你可以给出几个catch语句 - 每个例外。最后,你可以最后给出 - 这个语句将在Try块之后执行,不管异常是否被抛出或被捕获。
语法可以是这样的:
try{
try_statements
}
[catch (exception_var_2) { catch_statements_1 }]
[catch (exception_var_2) { catch_statements_2 }]
...
[catch (exception_var_2) { catch_statements_N }]
[finally { finally_statements }]
例子:
try {
myroutine(); // may throw three exceptions
} catch (e if e instanceof TypeError) {
// statements to handle TypeError exceptions
} catch (e if e instanceof RangeError) {
// statements to handle RangeError exceptions
} catch (e if e instanceof EvalError) {
// statements to handle EvalError exceptions
} catch (e) {
// statements to handle any unspecified exceptions
logMyErrors(e); // pass exception object to error handler
}
你可以在这里阅读更多:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
非常感谢。我会尝试一下代码。 – 2014-11-05 12:16:01
这个try catch配方是非标准的,只有mozilla(Firefox)。 – 2017-07-14 13:37:13
尝试捕获并没有为我工作。我个人最终测试了响应==“”和状态== 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 go 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;
您是否使用任何JavaScript框架,如jQuery或MooTools?如果没有,也许可以考虑,因为他们在AJAX功能中内置了成功/错误处理功能,并且可以处理跨浏览器问题等。 – WizzHead 2014-11-05 12:08:01
不幸的是,我不喜欢任何框架。我想用纯JS) – 2014-11-05 12:17:13