Window.unload在卸载后触发post

ind*_*dex 7 javascript jquery ruby-on-rails

我正在尝试在卸载页面之前对服务器发帖,然后我按照这个并且它工作正常.我的问题是关于window.unload的$.员额被触发它已卸载.我尝试使用注销链接并检查我的日志,我得到以下内容:

Started GET "/signout" for 127.0.0.1 at 2012-11-22 00:15:08 +0800
Processing by SessionsController#destroy as HTML
Redirected to http://localhost:3000/
Completed 302 Found in 1ms


Started GET "/" for 127.0.0.1 at 2012-11-22 00:15:08 +0800
Processing by HomeController#index as HTML
  Rendered home/index.html.erb within layouts/application (0.4ms)
  Rendered layouts/_messages.html.erb (0.1ms)
Completed 200 OK in 13ms (Views: 12.9ms)


Started POST "/unloading" for 127.0.0.1 at 2012-11-22 00:15:08 +0800
Processing by HomeController#unloading as */*
  Parameters: {"p1"=>"1"}
WARNING: Can't verify CSRF token authenticity
Completed 500 Internal Server Error in 0ms

NoMethodError (undefined method `id' for nil:NilClass):
  app/controllers/home_controller.rb:43:in `unloading'
Run Code Online (Sandbox Code Playgroud)

第一部分是注销,然后用户被重定向到root 然后它运行帖子('/ unloading').

有没有办法让'/ unloading'先执行然后执行任何卸载操作?

我有这个作为我的jquery帖子

$(window).unload ->
  $.ajax {
    async: false,
    beforeSend: (xhr) ->
      xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))
    , url: '/unloading'
    , type: 'Post'
    , data: {
      p1: '1'
    }
  }
Run Code Online (Sandbox Code Playgroud)

更新

所以我确实将ajax请求转移到beforeunload并且它正在工作但是我必须做一个return null删除出现的对话框,因为如果我不这样做,ajax仍然在弹出对话框时触发(即使没有回答"是/否我想离开这个页面").结果如下:

window.onbeforeunload ->
  $.ajax {
    async: false,
    beforeSend: (xhr) ->
      xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))
    , url: '/unloading'
    , type: 'Post'
    , data: {
      p1: '1'
    }
  }
  return null
Run Code Online (Sandbox Code Playgroud)

此外,我现在只尝试使用Chrome,它按预期工作.然而,尝试其他浏览器.

nic*_*son 9

试试这个beforeUnload活动

卸载事件的确切处理因浏览器的版本而异.例如,某些版本的Firefox会在跟踪链接时触发事件,但不会在窗口关闭时触发.在实际使用中,应该在所有支持的浏览器上测试行为,并与专有的beforeunload事件进行对比.

UPDATE

卸载页面时会触发卸载事件.

更新2

要禁用Are you sure that you want to leave this page?弹出窗口,请尝试nullbeforeUnload回调函数返回

更新3

检查这是否具有跨浏览器兼容性