【问题标题】:javascript onbeforeunload fire get request [duplicate]javascript onbeforeunload fire获取请求[重复]
【发布时间】:2013-01-18 16:06:09
【问题描述】:

可能重复:
How to execute ajax function onbeforeunload?
How to capture browser close event and make a request to web service method on that event through javascript

所以现在这就是我的 onbeforeunload 的样子

window.onbeforeunload = function (e) {
  var message = "Don't close me!",
  e = e || window.event;
  // For IE and Firefox
  if (e) {
    e.returnValue = message;
  }
  // For Safari
  return message;
};

所以这就是我想要做的,这个函数会触发并提示他们选择是否离开页面。当且仅当他们决定离开时,我需要触发 GET 请求以关闭数据库记录。

如果我这样设置,则通过测试:

window.onbeforeunload = $.get("url_here")

这是一个简单的解决方法,但是现在我无法获得提示,并且窗口在没有警告的情况下关闭。

我也尝试添加一个带有确认功能的功能,但它似乎无法正常工作。例如

window.onbeforeunload = function(e){
  if(confirm("Are you sure?")){
    $.get("url_here");

    return true;
  }
}

这个变得更奇怪了,但是在大多数情况下,它只会导致一条消息弹出一个带有是/否提示的文字文本(“true”)。

【问题讨论】:

标签: javascript jquery html


【解决方案1】:

看看这个:http://jsfiddle.net/3kvAC/241 和这个Dialog box runs for 1 sec and disappears? 和这个http://msdn.microsoft.com/en-us/library/ie/ms536907(v=vs.85).aspx

看起来像这样:

$(window).bind('beforeunload', function(){
  return 'Are you sure you want to leave?';
});

$(window).unload(function(){
  alert('Bye.');
});

【讨论】:

    猜你喜欢
    • 2018-01-09
    • 2020-10-20
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    • 2016-09-19
    • 2013-10-02
    • 2013-04-06
    • 1970-01-01
    相关资源
    最近更新 更多