【问题标题】:Intercepting ajax call when ajax request goes after complete page load, also xhr interceptor and ajax start are not working当 ajax 请求在完成页面加载后拦截 ajax 调用,xhr 拦截器和 ajax 启动也不起作用
【发布时间】:2021-09-03 16:37:23
【问题描述】:

我尝试使用 xhr 拦截器来修改 ajax 响应并在 ajax 响应之前进行一些处理。我的代码在早期工作,但现在不是。实际上我正在 bigcommerce 中开发应用程序,由于基石主题更新的一些变化,现在我的应用程序无法正常运行。 这是我使用的实际 xhr 拦截器:

var oldOpen = XMLHttpRequest.prototype.open;
function onStateChange(event) {
    console.log(this.responseURL);
    this.responseText = this.response;
    //I checked url here and did some process according to it
}
XMLHttpRequest.prototype.open = function() {
    this.addEventListener("readystatechange", onStateChange)
    Object.defineProperty(this, 'responseText', {
        writable: true
    });
    oldOpen.apply(this, arguments);
}

我也试过ajaxstart来解决这个问题:

$(document ).ajaxStart(function() {
  console.log('started');
});

Ajax 启动函数仅对页面加载期间调用的 ajax 请求执行。 当我点击按钮时,我希望 ajax 在页面加载后开始执行。默认情况下,单击此按钮,执行 ajax 请求(我从控制台检查,它是 xhr ajax)并打开模式。但不执行ajax启动。

还有一个问题,是jquery版本导致这个问题吗?我使用了 jquery 1.7.2。还没变。我也尝试了 1.12.4。 提前感谢您的帮助。

【问题讨论】:

    标签: jquery ajax xmlhttprequest interceptor bigcommerce


    【解决方案1】:

    你可以用 onreadystatechange 尝试这样的事情;

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
          if (xhr.readyState !== 4) return; {
              console.log(JSON.parse(xhr.responseText));
           }
    };
    xhr.open('GET', '/your/api/endpoint/here/');
    xhr.send();
    

    【讨论】:

    • 谢谢。但我没有发送请求。请求是由商店中的其他服务器发送的,我想拦截它并在它完成之前做一些处理。
    猜你喜欢
    • 2017-12-12
    • 2013-05-24
    • 2011-12-26
    • 1970-01-01
    • 1970-01-01
    • 2011-10-16
    • 1970-01-01
    • 1970-01-01
    • 2016-06-18
    相关资源
    最近更新 更多