onbeforeunload()
函数是否可以等待ajax结果并根据resultvalue移动到jsp,或者在卸载之前至少显示一条消息?
是否可以使用setTimeOut或某些自定义等待函数来解决此问题,或者我必须考虑其他一些工作流程
答案 0 :(得分:3)
使用a synchronous XmlHttpRequest call(“AJAX”是一个错误的人)。
答案 1 :(得分:0)
AFAIK,这是不可能的。 onbeforeunload
功能非常有限,否则恶意网站可能会阻止您离开其网站。
附录:可以显示“您要离开此页面”的消息。在这种情况下,beforeunload()
函数必须返回一个字符串。
实施例
window.onbeforeunload = function() {
return 'Are you sure about that?';
}
答案 2 :(得分:0)
从ajax显示等待响应的警告框并不好。通常,您可以使用警告框作为消息,以确认在ajax响应后离开页面。
为了避免使用警报,您可以同步调用Ajax,例如
if(window.XMLHttpRequest) xmlHttpObj=new XMLHttpRequest();
else xmlHttpObj=new ActiveXObject("Microsoft.XMLHTTP");
if(xmlHttpObj){
xmlHttpObj.onreadystatechange=function(){
if(xmlHttpObj.readyState==4 && xmlHttpObj.status == 200){
// your logic required
}
}
xmlHttpObj.open("GET", "your request url", false); // used false for synchronous call
xmlHttpObj.send(null);
}
else{
alert("AJAX not support");
}
答案 3 :(得分:0)
这是我的策略,对我有用:
_number_of_active_ajax ++;
$.ajax({
url: REQUEST_URL,
timeout: 3000
})
.always(function() {
_number_of_active_ajax --;
});
window.onbeforeunload = function() {
if(_number_of_active_debounce > 0 || _number_of_active_ajax > 0)
return "Your question";
}
}
如果页面有活动请求,它将显示要使用的消息。