我正在尝试在卸载页面之前向服务器发布一个帖子,我遵循了这个并且它工作正常。我的问题是 window.unload 上的 $.post 在卸载后触发。我尝试使用注销链接并检查我的日志,我得到以下信息:
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')。
有没有办法让“/卸载”先执行然后执行卸载操作?
我有这个作为我的 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 并且它正在工作,但我必须做一个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
另外,我现在只用 Chrome 尝试过它,它按预期工作。尚未尝试在其他浏览器上。