检查一个jQuery Ajax请求的状态状态、jQuery、Ajax

2023-09-10 17:20:34 作者:钢铁小伙伴

看来,成功,错误和完成回调时,Ajax请求能够从服务器获取一些响应。只火

所以,如果我关闭不执行下面的错误回调服务器并请求失败默默地。

  $。阿贾克斯({
  键入:GET,
  网址:HTTP://本地主机:3000 /,
  数据类型:剧本,
  成功:函数(){
    警报(成功);
  },
  错误:函数(){
    警报(错误);
  }
});
 

什么是扔在服务器根本无法达成一个错误的最好方法。

编辑 - 从我已经试过,看来,jQuery的内置的错误处理不与JSONP,或数据类型的工作内容如下:脚本。所以我要去尝试设置手动暂停。

编辑 - 做了一些更多的研究,它看起来像不仅阿贾克斯错误回调无法正常工作,但你不能中止由于数据类型的脚本或JSONP一个Ajax请求,这些请求忽略超时设置

还有一个另外的 - jQuery的-JSONP插件,但它使用隐藏的内置页框,我宁愿避免。所以我定居在创建手动超时的建议如下。你不能中止请求,如果超时,这意味着脚本甚至可以在超时后仍然加载,但至少东西会火,如果服务器不可用。

解决方案

您可以使用 的setTimeout ,并与 clearTimeout 在完整的处理程序。

  VAR reqTimeout = setTimeout的(功能()
{
  警报(请求超时。);
},5000);
VAR XHR = $阿贾克斯({
  键入:GET,
  网址:HTTP://本地主机:3000 /,
  数据类型:剧本,
  成功:函数(){
    警报(成功);
  },
  错误:函数(){
    警报(错误);
  },
  完成:函数(){
    clearTimeout(reqTimeout);
  }
});
 
温故jQuery Ajax,你会有新的发现

It seems that the success, error, and complete callbacks only fire when the ajax request is able to get some response from the server.

So if I shut down the server the following error callback is not executed and the request fails silently.

$.ajax({
  type: "GET",
  url: "http://localhost:3000/",
  dataType: "script",
  success: function() {
    alert("success");
  },
  error: function() {
    alert("error");
  }
});

What's the best way to throw an error when the server can't be reached at all.

Edit - From what I've tried and read it appears that jQuery's built in error handling doesn't work with JSONP, or dataType: "script". So I'm going to try setting a manual timeout.

Edit - Did a little more research and it looks like not only does the ajax error callback not work, but you can't abort an ajax request with dataType script or jsonp, and those requests ignore the timeout setting.

There is an alternative - the jquery-jsonp plugin, but it uses hidden iframes which I'd rather avoid. So I've settled on creating a manual timeout as suggested below. You can't abort the request if it times out, which means the script may still load even after the timeout, but at least something will fire if the server is unavailable.

解决方案

You can use a setTimeout, and clear it with clearTimeout in the complete handler.

var reqTimeout = setTimeout(function()
{
  alert("Request timed out.");
}, 5000);
var xhr = $.ajax({
  type: "GET",
  url: "http://localhost:3000/",
  dataType: "script",
  success: function() {
    alert("success");
  },
  error: function() {
    alert("error");        
  },
  complete: function() {
    clearTimeout(reqTimeout);
  }
});