检测XHR错误确实由于浏览器停止或单击新页 [英] Detect XHR error is really due to browser stop or click to new page

查看:1705
本文介绍了检测XHR错误确实由于浏览器停止或单击新页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的网页是通过XHR加载内容,如果用户点击停止按钮或点击到另一个页面,该XHR错误()函数被调用。这通常不会是一个大问题,除了看到许多(红色)错误消息的页面上的用户震撼。

While my page is loading content via XHR, if the user clicks the stop button or clicks to go to another page, the XHR error() function is called. This wouldn't normally be a big deal except for the user shock of seeing lots of (red) error messages on the page.

的消息是有效的 - 确实有检索内容的错误 - 但它由于用户交互,而不是因为系统故障的

The messages are valid - there was indeed an error retrieving the content - but it's due to the user interaction, not because of a system failure.

有没有一种方式来区分?(404 | 500 |超时错误)而造成的事实是,用户点击浏览器的停止按钮的误差

Is there a way to distinguish between a (404 | 500 | timeout error) and an error caused by the fact that the user hit the browser's stop button ?

编辑:我使用道场(因此误差函数引用),但我相信这将是一种情况,在任何XHR的实现是常见的。我会考虑XHR对象的readyState的错误时()被调用

I am using Dojo (hence the error function reference), but I believe this would be a situation that is common across any XHR implementation. I will look into readyState of the xhr object when error() is called

推荐答案

要HTTP错误( 404 401 403 500 ,等..),并要求人工流产的错误(即用户pressed Esc键或导航到其他页),您可以检查XHR.status属性,如果该请求已经中止的状态成员将是零:

To distinguish between HTTP errors (404, 401, 403, 500, etc..) and request abortion errors (i.e. the user pressed Esc or navigated to other page) , you can check the XHR.status property, if the request has been aborted the status member will be zero:

document.getElementById('element').onclick = function () { 
  postRequest ('test/', null, function (response) { // success callback
    alert('Response: ' + response); 
  }, function (xhr, status) { // error callback
    switch(status) { 
      case 404: 
        alert('File not found'); 
        break; 
      case 500: 
        alert('Server error'); 
        break; 
      case 0: 
        alert('Request aborted'); 
        break; 
      default: 
        alert('Unknown error ' + status); 
    } 
  }); 
};

一个简单的postRequest功能:

A simple postRequest function:

function postRequest (url, params, success, error) {  
  var xhr = XMLHttpRequest ? new XMLHttpRequest() : 
                             new ActiveXObject("Microsoft.XMLHTTP"); 
  xhr.open("POST", url, true); 
  xhr.onreadystatechange = function(){ 
    if ( xhr.readyState == 4 ) { 
      if ( xhr.status == 200 ) { 
    success(xhr.responseText); 
      } else { 
    error(xhr, xhr.status); 
      } 
    } 
  }; 
  xhr.onerror = function () { 
    error(xhr, xhr.status); 
  }; 
  xhr.send(params); 
}

这里运行上面的代码片段

Run the above snippet here.

这篇关于检测XHR错误确实由于浏览器停止或单击新页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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