重复XMLHttpRequest请求

时间:2018-06-22 20:11:57

标签: javascript xmlhttprequest

我的应用程序有一些jquery HTTP调用和一些有角度的HTTP调用。...

所以..要向每个请求添加参数,我将此代码添加到代码的开头。

var op = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function() {

    this.addEventListener("readystatechange", function() {

        if(this.readyState === 4 && this.status === 200 ){
            // http call is done
        }

    }, false);
    arguments[1] = arguments[1]+'?test=testParam';
    var resp = op.apply(this, arguments);
    return resp;
};

现在我想要两件事

1)我想先更改响应,然后再应用

2)如果响应为404 ....我想打另一个电话....接受响应...然后使用一些新参数重复该呼叫

1 个答案:

答案 0 :(得分:0)

简短的答案是,我们无法扩展XMLHttpRequest来重试连接,因为如果触发了.open事件,则无法触发.onload。编写同一.open实例的多个XMLHttpRequest会导致每个.open重写先前的.open,但是一旦触发.onload事件,我们将无法重用实例(请求不发送),因此我们必须创建另一个XMLHttpRequest实例。因此,我认为最接近的方法是重用代码,如下所示:

var param = 106;

var div = document.getElementById("retry");
var div2 = document.getElementById("success");
var div3 = document.getElementById("response");
div.innerHTML = "Trying: " + param;

var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/' + param);
xhr.onload = function() {
  if (this.status === 200) { //<-- we use this instead of xhr
    div2.innerHTML = "Success: " + param;
    div3.innerHTML = this.responseText;
  } else {
    var newXhr = xhr; //<-- we have to create another instance
    newXhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/' + param);
    newXhr.onload = xhr.onload; //<--we reuse the function
    newXhr.send();
    div.innerHTML = "Trying: " + param;
    param--;
  }
};
xhr.send();
<div id="retry">
</div>
<div id="success">
</div>
<div id="response">
</div>

这是另一种方法(我以前的回答),我认为更好:

function myAjax(param) {
  var div = document.getElementById("retry");
  var div2 = document.getElementById("success");
  var div3 = document.getElementById("response");
  div.innerHTML = "Trying: " + param;
  console.log(param);


  var xhr = new XMLHttpRequest();
  xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/' + param);
  xhr.onload = function() {
    if (xhr.status === 200) {
      div2.innerHTML = "Success: " + param;
      div3.innerHTML = xhr.responseText;
    } else {
      param--;
      myAjax(param); //I'm calling again the function
    }
  };

  xhr.send();
}

myAjax(105);
<div id="retry">

</div>
<div id="success">
</div>
<div id="response">
</div>