jQuery:如何让 ajaxSend 在继续之前等待另一个 Ajax 响应?

2024-02-13

我正在使用 jQuery (v.3.0.0),我需要ajax发送() http://api.jquery.com/ajaxsend/检查值是否存在于localStorage,将其添加到传出请求标头中。

如果该值不存在于localStorage, ajaxSend()应通过另一个 Ajax 请求获取此值,然后发送标头中包含正确值的原始请求。

这必须是一个全局处理程序,适用于发出的所有 jQuery Ajax 请求。

让我们来做一个代码示例。

$(document).ajaxSend(function (ev, req, opts) {
  // Before sending any jQuery Ajax request
  var original = req;
  if (localStorage.foo) {
    // If value "foo" is available, add it to the headers
    req.setRequestHeader('foo', localStorage.foo);
  } else {
    // Otherwise get it first, and add it to the headers
    $.get({url: '/foo', global: false})
      .done(function (data, textStatus, req) {
        // "foo" is received and added to the original request headers
        localStorage.foo = data;
        original.setRequestHeader('foo', data);
        // Now the original request is ready to be sent
      });
  }
});

When foo不可用,上面代码的问题在于,显然原始请求是在 的值之前发送出去的foo被检索到。

有什么办法可以解决这个问题并使其正常工作吗?

Thanks!!


到目前为止,这是我能找到的最佳解决方案。它并不完美,也没有完全回答最初的问题,但它是一个很好的解决方法,并且非常接近我想要实现的目标。

主要区别在于,它不是让原始请求等待,而是取消它,获取所需的值,然后创建一个与原始请求具有相同设置的新请求。

$(document).ajaxSend(function (ev, req, opts) {
  if (localStorage.foo) {
    // If value "foo" is available, add it to the headers
    req.setRequestHeader('foo', localStorage.foo);
  } else {
    // Otherwise cancel the original request, then get "foo",
    // and create a new request with the same settings as the original one
    req.abort();
    $.get({url: '/foo', global: false})
      .done(function (data, textStatus, req) {
        // "foo" is received
        localStorage.foo = data;
      })
      .then(function () {
        $.ajax(opts);
      });
  }
});

它工作完美。如果有人找到更好的解决方案,允许直接使用原始请求,我将很乐意编辑此答案并改进它。

Thanks!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

jQuery:如何让 ajaxSend 在继续之前等待另一个 Ajax 响应? 的相关文章

随机推荐