【问题标题】:Redirect user before success callback is received在收到成功回调之前重定向用户
【发布时间】:2016-02-19 13:26:39
【问题描述】:

这是我的代码:

$.ajax( {
    type: "POST",
    url: "/script.php",
    data: { "action" : "importData" },
    cache: false,
    async: true,
    success: function() {
        window.location.href = "/next-page";
    }
} );

当用户登陆此页面时,ajax 将触发 php 脚本,大约需要 15 秒才能完成。我不想让用户等待脚本完成然后重定向它们,而是希望得到某种类型的脚本已被触发的确认,然后重定向用户而不等待整个脚本完成。脚本的结果要等到工作流的几分钟后才会使用。

这可能吗?该怎么做?

【问题讨论】:

  • 默认不等待,只需将重定向移动到调用后(从成功中移除)

标签: php jquery ajax asynchronous


【解决方案1】:

$.ajax() 返回XMLHttpRequest 实例:

var xhr = $.ajax({
  type: 'POST',
  url: '/script.php',
  data: {action: 'importData'},
  cache: false,
  success: function(){
    location = '/next-page';
  }
});
/* to test if problem is jQuery remove this line and take comments out
var px = xhr.onreadystatechange;
*/
xhr.onreadystatechange = function(){
  //if(px)px();
  if(xhr.readyState === 3 && xhr.status === 200){ // look at Properties -> https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
    // do stuff here with xhr.readyState less than 4
  }
}

可以在here 中找到有效的XMLHttpRequest.readyState 属性值。

请注意,如果您重定向用户,当前页面上的 JavaScript 会停止。您的用户被重定向到的页面可能有它自己的 JavaScript。

【讨论】:

  • xhr.onreadystatechange 没有被调用,因此我的 window.location.href = "/next-page";在那个 if 语句中没有被执行?
  • xhr.onreadystatechange 会在 readyState 更改为 XMLHttpRequest 的特定实例时自动调用,xhr 在您的情况下。 $.ajax({}) 中的 success 方法在 xhr.readyState === 4 && xhr.status === 200) 时触发。如果success 没有执行,那可能是因为您在xhr.onreadystatechange 函数中发生的代码正在采取措施阻止它,或者jQuery 使用了与xhr.addEventListener 相同的分配方法。如果是jQuery 问题,无论如何我都有解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-17
  • 1970-01-01
  • 2014-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多