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'
第一部分是注销,然后用户被重定向到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' } }
更新
所以我确实将ajax请求转移到beforeunload并且它正在工作但是我必须返回null以删除出现的对话框,因为如果我不这样做,ajax仍然在弹出对话框时触发(即使没有回答“是/ /不,我想离开这个页面“).结果如下:
window.onbeforeunload -> $.ajax { async: false,data: { p1: '1' } } return null
另外,我现在只尝试使用Chrome,它按预期工作.然而,尝试其他浏览器.
解决方法
The exact handling of the unload event has varied from version to
version of browsers. For example,some versions of Firefox trigger the
event when a link is followed,but not when the window is closed. In
practical usage,behavior should be tested on all supported browsers,
and contrasted with the proprietary beforeunload event.
> https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeunload
UPDATE
卸载页面时会触发卸载事件.
更新2
要禁用“您确定要离开此页面吗?”弹出尝试从beforeUnload回调函数返回null
> How to show the “Are you sure you want to navigate away from this page?” when changes committed?
更新3
检查这是否具有跨浏览器兼容性
> http://jonathonhill.net/2011-03-04/catching-the-javascript-beforeunload-event-the-cross-browser-way/