0

当用户离开我的页面时,我需要做一些后端处理。我的 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){}
      });
   }
}

任何帮助将不胜感激。

4

1 回答 1

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){}
  });
}
}
于 2013-10-14T10:39:43.953 回答