【问题标题】:onClick, wait for existing XMLhttprequest() to completeonClick,等待现有的 XMLhttprequest() 完成
【发布时间】:2021-02-15 12:42:18
【问题描述】:

我在这个挑战中有点挣扎......

我需要做三件事:

  • 点击按钮/表单提交,等待下一页完成加载。
  • 然后,等待页面上现有的 API/GET 请求完成。
  • 然后检查该 API 请求的结果。

我遇到的问题是,当我单击按钮时,下一页甚至没有机会完成加载,我的 API 检查立即执行。

我查看了许多解决方案,async/wait,有些建议不要使用 setTimeOut。而且我似乎仍然无法克服第一个障碍,等待页面完成加载并允许现有的 API 调用完成。

如何等待现有 API 调用完成运行?

let button = document.getElementById("signin");
button.setAttribute("onClick", "fireTracking()");

function ajax(url) {
    return new Promise(function(resolve, reject) {
      var xhr = new XMLHttpRequest();
      xhr.onload = function() {
        resolve(this.responseText);
      };
      xhr.onerror = reject;
      xhr.open('GET', url);
      xhr.send();
    });
  }
  
function fireTracking() {
    ajax("www.myurl.com/getstatus")
    .then(function(result) {
    // Code depending on result
    console.log(result);
    console.log("fire event...")
  })
  .catch(function() {
    // An error occurred
  });
}

为了混淆,页面的 URL 是相同的。所以本质上,我无法寻找不同的 URL。

我开始认为我可能需要使用 setTimeout? IE,等待1秒再进行新的api调用?

请注意,这是在应用程序之上运行的代码。我正在使用 AB 测试工具,所以我基本上是在尝试让它在已经编译的代码之上工作。

【问题讨论】:

  • button.setAttribute("onClick", "fireTracking()"); 不要使用 setAttribute 绑定事件
  • @epascarello 你好,为什么不呢?到目前为止它似乎运行良好......由于我正在使用的应用程序,我不得不通过 DOM 操作来做到这一点。如果不插入 onclick,这将无法在移动设备上运行。我之前使用的是事件监听器...
  • 因为正确的方法是使用 addEventListener
  • 我没有完全关注您的问题,但表单按钮上的preventing the default 在这些情况下通常很有用。
  • 只需删除 type="submit" 属性或使用 event.preventDefault()。顺便说一句,最好将你的 fireTracking() 函数绑定到表单的提交事件。

标签: javascript api xmlhttprequest fetch


【解决方案1】:

该按钮正在提交form,同时触发您的fireTracking 函数。

所以...该提交正在刷新您的页面,而 Ajax 请求的结果就丢失了。

你必须prevent the normal submit behavior

所以这是对您的代码进行的“最小更改”:

let button = document.getElementById("signin");
button.setAttribute("onClick", "fireTracking(event)");  // Add the event argument

function ajax(url) {
    return new Promise(function(resolve, reject) {
      var xhr = new XMLHttpRequest();
      xhr.onload = function() {
        resolve(this.responseText);
      };
      xhr.onerror = reject;
      xhr.open('GET', url);
      xhr.send();
    });
  }
  
function fireTracking(event) {  // Add the event argument
    event.preventDefault()  // Add this
    ajax("www.myurl.com/getstatus")
    .then(function(result) {
    // Code depending on result
    console.log(result);
    console.log("fire event...")
  })
  .catch(function() {
    // An error occurred
  });
}

但是!一个好的做法是使用.addEventListener() 为该按钮设置一个事件处理程序,就像提到的@epacarello。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 2020-07-04
    • 2011-12-28
    • 2011-09-08
    • 1970-01-01
    相关资源
    最近更新 更多