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

前端之家收集整理的这篇文章主要介绍了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/

猜你在找的JavaScript相关文章