gpt4 book ai didi

javascript - Window.unload 触发后卸载

转载 作者:数据小太阳 更新时间:2023-10-29 04:27:55 31 4
gpt4 key购买 nike

我正在尝试在卸载页面之前向服务器发帖,然后我关注了 this它工作正常。我的问题是 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')。

有没有办法让 '/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 上尝试过,它按预期工作。尚未尝试其他浏览器。

最佳答案

尝试 beforeUnload 事件

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.

更新

卸载页面时触发卸载事件。

更新 2

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

更新 3

检查跨浏览器兼容性

关于javascript - Window.unload 触发后卸载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13506142/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com