Detect XHR error is really due to browser stop or click to new page

前端 未结 1 752
花落未央
花落未央 2021-02-05 05:48

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 bi

相关标签:
1条回答
  • 2021-02-05 06:01

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

    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.

    0 讨论(0)
提交回复
热议问题