onbeforeunload等待ajax结果

onbeforeunload等待ajax结果

问题描述:

onbeforeunload()函数可能等待ajax结果并根据结果值移动到jsp或至少在卸载之前显示消息?onbeforeunload等待ajax结果

是否有可能使用的setTimeout或一些自定义等待功能对于这个问题,或者我要考虑一些其他的工作流程

+0

也许与同步调用 – mplungjan 2011-03-15 10:37:05

使用a synchronous XmlHttpRequest call( “AJAX” 是一个误nomer)。

+0

谢谢,我会尝试 – anu 2011-03-15 10:56:29

据我所知,那是不可能的。 onbeforeunload的功能非常有限,否则恶意网站可能会阻止您离开其网站。

附录:可能会显示一条消息,如'您要离开本页面'。在这种情况下,beforeunload()函数必须返回一个字符串。

window.onbeforeunload = function() { 
    return 'Are you sure about that?'; 
} 
+0

实际上,该消息包含ajax结果的一些内容。无论如何,我认为这个工作流程不好,我将使用redirectAction并使用其他一些技巧显示消息 – anu 2011-03-15 10:54:54

这是不好的想法显示警报框等待来自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"); 
}  

这是我的策略和对我的作品:

_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"; 
} 

}

它会显示一个消息如果页面具有活动请求,请使用此选项。