在服务器beforeunload之前发送AJAX [英] Send AJAX to server beforeunload

查看:131
本文介绍了在服务器beforeunload之前发送AJAX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以应该从Firefox开始> 4 ,将窗口jQuery对象绑定到 beforeunload 不再工作了。

So supposedly starting at Firefox > 4, binding the window jQuery object to beforeunload doesn't work anymore.

我想要做的是提交一个AJAX帖子删除我的服务器的内存缓存数据。

What'd I'd like to do is submit an AJAX post to delete my server's memcache data.

当我刷新唯一打开的选项卡时,我可以看到 beforeunload 在firefox和chrome中使用以下代码,如console.log消息firefox / NON-firefox delete所证明的。问题是我从来没有看到console.log消息memcache delete,表明我的服务器从未见过 $。ajax 请求。

When I refresh the only open tab, I can see that the beforeunload event is called in both firefox and chrome with the following code as evidenced by the console.log message, "firefox/NON-firefox delete". The problem is that I never see the console.log message "memcache delete" indicating that my server never saw the $.ajax request.

我意识到做浏览器嗅探是不好的,并且if和else语句中包含的内容没有什么区别。我只是显示我在Firefox中尝试失败的代码。

I realize it is bad to do browser sniffing and that there is no difference between what's included in the if and else statements. I'm merely showing code for what I've tried unsuccessfully in Firefox.

任何人都有什么想法?

$(window).bind('beforeunload', function(){ 
  if(/Firefox[\/\s](\d+)/.test(navigator.userAgent) && new Number(RegExp.$1) >= 4) {
    console.log('firefox delete');
     memcacheDelete();
     return null;
  } 
  else {
    console.log('NON-firefox delete');
    memcacheDelete();
    return null;
  }
});

function memcacheDelete() {
   $.ajax({
      url: "/memcache/delete", 
      type: "post",
      data:{}, 
      success:function(){
          console.log('memcache deleted');
      }//success
  }); //ajax
}


推荐答案

Ajax是异步的。

Ajax is asynchronous.

当您刷新(或关闭)浏览器时, beforeunload 正在调用。这意味着 beforeunload 完成执行后,页面将刷新(或关闭)。

When you refresh (or close)your browser, beforeunload is being called. And it means as soon as beforeunload is finished executing, page will refresh (or close).

ajax请求,(因为它的异步)javascript解释器不等待ajax 成功事件被执行,并向下移动完成执行 beforeunload

When you do an ajax request, (since its asynchronous) javascript interpreter does not wait for ajax success event to be executed and moves down finishing the execution of beforeunload.

成功的ajax应该在几秒钟后被调用,但是你不会看到它,因为页面已经刷新/已关闭。

success of ajax is supposed to be called after few secs, but you dont see it as page has been refreshed / closed.

附注:

.success()方法已弃用,并由 .done()方法

.success() method is deprecated and is replaced by the .done() method

参考

这篇关于在服务器beforeunload之前发送AJAX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆