我正在使用java-script window.onbeforeunload
函数在用户尝试离开页面而不提交数据时向用户显示警报。此功能正常。
我遇到问题,而ajax响应从服务器页面收到并置于成功回调函数中,然后我使用window.location.href
功能重新加载该窗口页面
window.location.href=baseurl+'index.php/functionname/'+arg_id;
当页面重新加载到另一个页面时,它显示了对话框部分 这是我的ajax功能:
$.ajax({
type: "POST",
url: baseurl+"index.php/sample/samplefunction",
data: {"demo_detail":sse,'demo_detail':pro},
success:function(data) {
if(data) {
window.location.href=baseurl+'index.php/functionname/'+arg_id;
}
}
});
这是我的工作window.onbeforeunload
功能
window.onbeforeunload = confirmExit;
function confirmExit()
{
return "You have attempted to leave this page. Are you sure you want to exit this page?";
}
如何使用 javascript
阻止window.onbeforeunload
中的ajax response
功能
答案 0 :(得分:2)
您可以按如下方式使用全局变量:
var confirm = true;
在你的ajax响应中,确认为false,如下所示:
$.ajax({
type: "POST",
url: baseurl+"index.php/sample/samplefunction",
data: {"demo_detail":sse,'demo_detail':pro},
success:function(data) {
if(data) {
confirm = false;
window.location.href=baseurl+'index.php/functionname/'+arg_id;
}
}
});
在你的" comfirmExit()"功能,如果确认是尝试,则检查,然后仅向用户发出警告。
window.onbeforeunload = confirmExit;
function confirmExit()
{
if(confirm)
return "You have attempted to leave this page. Are you sure you want to exit this page?";
else
return;
}
答案 1 :(得分:1)
您可以在AJAX回调中关闭处理程序:
if(data) {
window.onbeforeunload = undefined;
window.location.href=baseurl+'index.php/functionname/'+arg_id;
}