当用户离开页面时,我需要在离开前询问他是否要执行特定操作。
<script type="text/javascript">
$(document).ready(function() {
window.onbeforeunload = askConfirm;
});
function askConfirm() {
var addFriend = confirm("Would you like to ping?");
if (addFriend) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","http://example.com?ping=1234",true);
xmlhttp.send();
}
return null;
}
取决于最后一个 return
语句的值(""
、null
、true
、false
,或者根本没有 return
语句)我可能遇到以下两种情况之一:
1) 用户得到“你想ping吗?”确认(好),发送 ping(好),用户看到“此页面要求您确认是否要离开”弹出窗口(坏)。
-或-
2) 用户得到“你想ping吗?”确认(良好),ping 未发送(错误),并且用户未显示“此页面要求您确认您要离开”弹出窗口(好)。
我怎样才能发送 AJAX ping,同时抑制“此页面要求您确认是否要离开”弹出窗口?
编辑:虽然听起来很荒谬,但我发现针对此问题的“变通办法”是在 xmlhttp.send( )
语句。唯一干净的方法是提醒用户他的 ping 已发送。如果 future 的 StackOverflowers 找到更好的解决方案,我很想知道。
谢谢。
最佳答案
您可以使 Ajax 请求同步。
xmlhttp.open("GET","http://example.com?ping=1234", false); // use false here
xmlhttp.send();
如果您的服务器速度较慢,可能会造成轻微的延迟,但它应该可以解决无法发送 ping 的问题。
关于Javascript:在 onbeforeunload 上抑制 "This page is asking you to confirm that you want to leave"弹出窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9219800/