javascript – Window.unload在卸载后触发post

我正在尝试在卸载页面之前对服务器发帖,然后我按照 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并且它正在工作但是我必须返回null以删除出现的对话框,因为如果我不这样做,ajax仍然在弹出对话框时触发(即使没有回答“是/ /不,我想离开这个页面“).结果如下:

window.onbeforeunload ->
  $.ajax {
    async: false,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.

> https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeunload

UPDATE

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

> https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Synchronous_and_Asynchronous_Requests#XMLHttpRequests_being_stopped

更新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/

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...