当用户离开我的页面时,我需要做一些后端处理。我的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){}
});
}
}
任何帮助将不胜感激。
答案 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){}
});
}
}