用JS离开页面后做一些事情

时间:2013-10-14 10:05:53

标签: javascript php jquery frontend

当用户离开我的页面时,我需要做一些后端处理。我的JS代码工作正常:

if (window.addEventListener) {  // all browsers except IE before version 9
    window.addEventListener("beforeunload", OnBeforeUnLoad, false);
}
else {
    if (window.attachEvent) {   // IE before version 9
        window.attachEvent("onbeforeunload", OnBeforeUnLoad);
    }
}

function OnBeforeUnLoad () {
    return "Are you sure?";
}

但是当用户在浏览器提示的对话框上按OK时,我的OnBeforeUnLoad函数必须包含$.ajax调用以在服务器端执行某些操作。这样做不起作用:

function OnBeforeUnLoad () {
   if (confirm("Are you sure?")){
      $.ajax({
         type:       "POST",
         url:        "../wp-content/scripts/removedemo.php",
         data:       "s="+UserSession.encodedurl,
         success: function(data){}
      });
   }
}

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

使用setimeout函数延迟执行秒数。这是你的代码:

setTimeout(OnBeforeUnLoad, 10); 

function OnBeforeUnLoad () {
if (confirm("Are you sure?")){
  $.ajax({
     type:       "POST",
     url:        "../wp-content/scripts/removedemo.php",
     data:       "s="+UserSession.encodedurl,
     success: function(data){}
  });
}
}