如何使用XMLHttpRequest捕获无效URL引发的错误 [英] How to catch the error thrown by an invalid URL using XMLHttpRequest
问题描述
我对 JavaScript
中的 XMLHttpRequest
对象没有做太多的工作.我是新来的.我已经完成了许多 jQuery
Ajax
调用,但是对于 XMLHttpRequest
对象的工作还不够详细.
I have not worked much with the XMLHttpRequest
object in JavaScript
. I am new to it. I have done many jQuery
Ajax
calls, but have not worked in much detail with the XMLHttpRequest
object.
我正在研究一本书,他们在其中提供了使用此对象的一些示例代码.
I am working through a book where they give some sample code using this object.
这是本书尝试处理错误时使用的一些代码.它应该能够捕获由不正确的URL引发的错误.但我无法接受 catch子句
:
Here is some code the book uses when trying to deal with errors. It is supposed to catch the error thrown by the incorrect URL. But I can't get it to go it the catch clause
:
var httpRequest = new XMLHttpRequest();
try
{
httpRequest.open("GET", "http://");
httpRequest.send();
}
catch (error)
{
alert("in catch clause");
}
我什至尝试了无效的URL,但仍然不想进入 catch子句
:
I have even tried an invalid URL and still doesn't want to go into the catch clause
:
httpRequest.open("GET", "gttp://");
是因为URL是一个有效的URL,它没有引发异常吗?
Is it because the URL is a valid URL that it is not throwing an exception?
推荐答案
var httpRequest = new XMLHttpRequest();
try
{
httpRequest.open("GET", "http://",false);
httpRequest.send();
}
catch (error)
{
alert("in catch clause");
}
默认的 open
方法是异步的,无法在try/catch块中捕获.这是因为即使在open方法完成之前,整个代码也将被执行. open
方法还有一个名为 async
的可选参数,该参数为布尔值,默认为 true
.将其设置为 false
即可完成工作.如果该值为false,则在收到响应之前, send()
方法不会返回.
The default open
method is asynchronous and cannot be caught in try/catch block. This is because the entire code will get executed even before the open method is completed. open
method has got another optional parameter called async
which is boolean and default is true
. Setting it to false
will get the job done. If this value is false, the send()
method does not return until the response is received.
这篇关于如何使用XMLHttpRequest捕获无效URL引发的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!