xmlHttpRequest.onerror处理程序用例

Dev*_*per 5 javascript ajax xmlhttprequest onerror

哪种情况会导致调用此处理程序?我找不到此方法引发错误的任何实例。

我尝试离线使用设备,xmlHttpRequest.status = 0但没有出现错误。

问题是我可以创建哪种情况来测试此处理程序的功能。

var xmlhttp = new XMLHttpRequest(),
  method = 'GET',
  url = 'https://developer.mozilla.org/';

xmlhttp.open(method, url, true);
xmlhttp.onerror = function () {
  console.log("** An error occurred during the transaction");
};
xmlhttp.send();
Run Code Online (Sandbox Code Playgroud)

来自:https : //developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequestEventTarget/onerror

Ale*_*ins 9

你的问题就是一个很好的例子。只需在此页面上从您的 Web 开发人员控制台尝试您的代码。

在此处输入图片说明

在这里,你自己试试:

var xmlhttp = new XMLHttpRequest(),
  method = 'GET',
  url = 'https://developer.mozilla.org/';

xmlhttp.open(method, url, true);
xmlhttp.onerror = function () {
  console.log("** An error occurred during the transaction");
};
xmlhttp.send();
Run Code Online (Sandbox Code Playgroud)

在处理任何基于网络的 IO 时,各种事情都可能发生。跨域请求只是一种。如果服务器离线,DNS 查找失败,您和服务器之间的路由器(作为关键故障点)出现故障怎么办?

  • onerror 仅在网络级别发生错误时触发。任何 HTTP 代码,包括 400 及以上都不会*触发 onerror。 (16认同)