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

标签 javascript jquery ajax asynchronous

我正在使用 jQuery (v.3.0.0),我需要 ajaxSend()检查 localStorage 中是否存在值,将其添加到传出请求 header 中。

如果该值不在 localStorage 中,ajaxSend() 应该使用另一个 Ajax 请求获取该值,然后在 header 中发送带有正确值的原始请求.

这必须是一个全局处理程序,适用于所有发出的 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
      });
  }
});

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

有什么方法可以解决这个问题并让它正常工作吗?

谢谢!!

最佳答案

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

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

$(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);
      });
  }
});

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

谢谢!

关于javascript - jQuery:如何让 ajaxSend 在继续之前等待另一个 Ajax 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32643469/

相关文章:

javascript - UITableViewCell 中的 UIWebView 仅完成第一个单元格中的加载

javascript - 什么决定了确认/警报的呈现?

jquery - 禁用左括号的 keydown

javascript - 在对象中搜索关联数据

javascript - 类型错误 : f is undefined

javascript - 每秒“重新启动”jQuery?

javascript - Deferred Promise - 在每个函数完成后一个一个地运行函数

javascript - ajax使用json数据自动更新表

javascript - 如何在 ajaxSend 中正确添加数据参数?

ajax - 显示 localStorage 缓存中的数据,然后使用服务中的 AJAX 结果进行更新