onbeforeunload等待ajax结果

onbeforeunload()函数是否可以等待ajax结果并根据resultvalue移动到jsp,或者在卸载之前显示一条消息?

是否可以使用setTimeOut或一些自定义等待函数来解决此问题,或者我必须考虑其他一些工作流程

使用同步XmlHttpRequest调用 (“AJAX”是一个错误的用法)。

AFAIK,这是不可能的。 onbeforeunloadfunction非常有限,否则恶意网站可能会阻止您离开他们的网站。

附录:可以显示“您要离开此页面”的消息。 在这种情况下, beforeunload()函数必须返回一个字符串。

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

从ajax等待响应显示警告框并不好。 通常,您可以使用警告框作为消息,以确认ajax响应后的Leaving页面。

为避免使用警报,您可以同步调用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"; } 

}

如果页面有活动请求,它将显示要使用的消息。