代码之家  ›  专栏  ›  技术社区  ›  olore

检测xhr错误实际上是由于浏览器停止或单击到新页面造成的。

  •  21
  • olore  · 技术社区  · 17 年前

    当我的页面通过xhr加载内容时,如果用户单击停止按钮或单击转到另一个页面,则调用xhr error()函数。这通常不会有什么大不了的,除了用户在页面上看到大量(红色)错误消息时感到震惊之外。

    这些消息是有效的——确实在检索内容时出错了——但这是由于用户交互,而不是系统故障。

    是否有办法区分(404 500超时错误)和用户点击浏览器停止按钮导致的错误?

    编辑:我使用的是Dojo(因此是错误函数引用),但我相信这在任何XHR实现中都是常见的情况。当调用error()时,我将研究xhr对象的readystate。

    1 回复  |  直到 17 年前
        1
  •  35
  •   Christian C. Salvadó    17 年前

    区分HTTP错误( 404 , 401 ,请 403 , 500 等)和请求中止错误(即用户按下Esc或导航到其他页面),您可以检查xhr.status属性,如果请求已中止,则状态成员将为零:

    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函数:

    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); 
    } 
    

    运行上面的代码段 here .