【问题标题】:Repeat XMLHttpRequest request重复 XMLHttpRequest 请求
【发布时间】:2018-08-01 23:04:18
【问题描述】:

我的应用有一些 jquery http 调用和一些 angular 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....我想打另一个电话....接受响应...然后用一些新参数重复调用

【问题讨论】:

    标签: javascript xmlhttprequest


    【解决方案1】:

    简短的回答是我们不能扩展XMLHttpRequest 来重试连接,因为如果我们触发了.onload 事件,我们就不能触发.open。写几个.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>

    【讨论】:

    • 这超出了主题.....我正在尝试制作拦截器,而不是递归调用
    • @Michalis 我已经更新了答案以更适合您的问题。
    猜你喜欢
    • 2013-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-26
    • 2011-04-26
    • 2011-12-23
    • 2012-02-06
    相关资源
    最近更新 更多