如何检测浏览器中 AJAX (XmlHttpRequest) 调用的超时时间? [英] How to detect timeout on an AJAX (XmlHttpRequest) call in the browser?

查看:39
本文介绍了如何检测浏览器中 AJAX (XmlHttpRequest) 调用的超时时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在网上查找,但很难找到文档.我们都知道使用浏览器内置的 XMLHttpRequest 对象进行基本的 AJAX 调用(这里假设是现代浏览器):

I'm looking on the web, but documentation is hard to come by. We all know the basic AJAX call using the browser's built-in XMLHttpRequest object (assume a modern browser here):

var xmlHttp = new XMLHttpRequest();  // Assumes native object

xmlHttp.open("GET", "http://www.example.com", false);

xmlHttp.send("");

var statusCode = xmlHttp.status;
// Process it, and I'd love to know if the request timed out

那么,有没有一种方法可以通过检查浏览器中的 XMLHttpRequest 对象来检测 AJAX 调用是否超时?我会被建议做类似 window.setTimeout(function() { xmlHttp.abort() }, 30000); 之类的事情吗?

So, is there a way that I can detect that the AJAX call timed out by inspecting the XMLHttpRequest object in the browser? Would I be advised to do something like window.setTimeout(function() { xmlHttp.abort() }, 30000);?

谢谢!

-迈克

推荐答案

更新: 这里是 一个如何处理超时的示例:

var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://www.example.com", true);

xmlHttp.onreadystatechange=function(){
   if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
      clearTimeout(xmlHttpTimeout); 
      alert(xmlHttp.responseText);
   }
}
// Now that we're ready to handle the response, we can make the request
xmlHttp.send("");
// Timeout to abort in 5 seconds
var xmlHttpTimeout=setTimeout(ajaxTimeout,5000);
function ajaxTimeout(){
   xmlHttp.abort();
   alert("Request timed out");
}

在 IE8 中,您可以添加 超时 XMLHttpRequest 对象的事件处理程序.

In IE8, You can add a timeout event handler to the XMLHttpRequest object.

var xmlHttp = new XMLHttpRequest();
xmlHttp.ontimeout = function(){
  alert("request timed out");
}

我建议不要像您的代码所暗示的那样进行同步调用,并建议使用 javascript 框架来执行此操作.jQuery 是最受欢迎的一种.它使您的代码更高效、更易于维护和跨浏览器兼容.

I would recommend against making synchronous calls as your code implies and also recommend using a javascript framework to do this. jQuery is the most popular one. It makes your code more efficient, easier to maintain and cross-browser compatible.

这篇关于如何检测浏览器中 AJAX (XmlHttpRequest) 调用的超时时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆