且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当所有xmlHttpRequests完成时执行函数

更新时间:2023-11-20 23:06:10

工作解决方案

我们可以使用以下代码跟踪浏览器 AJAX 的调用:

We can track browser AJAX calls using the code below :

  const ajaxCallStatus = () => {
   window.ajaxCalls = 0; // initial ajax calls
   window.ajaxEndpoints = []; // keeping track of all ajax call urls (endpoints) 
   const origOpen = XMLHttpRequest.prototype.open;
   XMLHttpRequest.prototype.open = function() {
   window.ajaxCalls++;
   this.addEventListener('load', (event) => {
    if (!window.ajaxEndpoints.includes(event['currentTarget'].responseURL)) {
      window.ajaxEndpoints.push(event['currentTarget'].responseURL);
    }
    window.ajaxCalls--;
    switch (window.ajaxCalls) {
    case 0: // when ajax calls finish this runs
      addData(window.ajaxEndpoints);
    break;
    }
     });
    origOpen.apply(this, arguments);
    }
   }

添加数据功能-用于将数据发送到某些后端.

ADD DATA FUNCTION - Used for sending data to some backend.

function addData(arr, origOpen) { 
   XMLHttpRequest.prototype.open = origOpen;
   axios.post('url', data)
  .then((res) => console.log(res))
  .catch((err) => console.log(err));
}