【问题标题】:How to catch the error thrown by an invalid URL using XMLHttpRequest如何使用 XMLHttpRequest 捕获无效 URL 引发的错误
【发布时间】:2017-03-13 05:47:52
【问题描述】:

我对@9​​87654323@ 中的XMLHttpRequest 对象工作不多。我是新手。我已经完成了很多 jQuery Ajax 调用,但没有对 XMLHttpRequest 对象进行过详细的处理。

我正在阅读一本书,他们提供了一些使用此对象的示例代码。

这是本书在尝试处理错误时使用的一些代码。它应该捕获由不正确的 URL 引发的错误。但我不能让它去catch clause

var httpRequest = new XMLHttpRequest();
try
{
     httpRequest.open("GET", "http://");
     httpRequest.send();
}
catch (error)
{
     alert("in catch clause");
}

我什至尝试了一个无效的 URL,但仍然不想进入 catch clause

httpRequest.open("GET", "gttp://");

是不是因为该 URL 是一个有效的 URL 才没有抛出异常?

【问题讨论】:

  • 传递未定义变量httpRequest.open("GET", not_defined);时捕获的错误
  • 我试过 httpRequest.open("GET", false); 它调用 OS/false 和 null 和 undefined 相同。

标签: javascript ajax html xmlhttprequest


【解决方案1】:

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() 方法不会返回。

【讨论】:

    猜你喜欢
    • 2020-01-23
    • 1970-01-01
    • 2015-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-28
    • 1970-01-01
    • 2022-08-18
    相关资源
    最近更新 更多