weixin_33690963 2019-06-30 12:45 采纳率: 0%
浏览 548

关闭特定的XMLHttpRequest

How to "rebuild" function to close specific XMLHttpRequest? I have defined variable outside function to call xhr.abort(); everywhere I need. Now is possible, with this solution, close last running XMLHttpRequest if running more than one at same time - processes before last running are without control after replace xhr by re-calling _ajax()

var xhr;

function _ajax(data, callback) {
  xhr = new XMLHttpRequest();
  xhr.open('POST', window.location.pathname, true);
  xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      callback(this);
    }
  };
  xhr.send(data);
}

/* close fnc */
xhr.abort();
  • 写回答

1条回答 默认 最新

  • weixin_33720452 2019-06-30 13:29
    关注

    You could use xhr as an array and store there all the requests; then you can call abort on any one of them. Like:

    var xhr=[];
    function _ajax(data, callback) {
        xhr.push(new XMLHpptRequest);
        //etc
    }
    xhr[0].abort();
    xhr.shift(); //get rid of the aborted request
    
    评论

报告相同问题?