AJAX调用onbeforeunload以保存数据 [英] AJAX call on onbeforeunload to save data
问题描述
我有一个页面,用户在其中执行一些活动(添加/更新/删除),并且在页面卸载后(实际上是刷新/离开),我进行了AJAX调用以保存数据.下面是代码;
I have a page where a user performs some activity (Add/Update/Delete) and on unload of the page (actually refresh/navigating away) I make an AJAX call to save the data. Below is the code;
window.onbeforeunload = function () {
someAjaxObj.saveFavorites(json,{async:false}); // use async:false else callback is returned to an unloaded page creating a dwr javascript error
}
现在由于某些原因,在iPad Safari上刷新后,数据无法保存/反映.我曾尝试将iPad的"onbeforeunload"更改为"pagehide",但刷新后仍然无法反映数据.
Now for some reasons, the data does not get saved/reflected after refresh on iPad Safari. I tried changing "onbeforeunload" to "pagehide" for iPad, but still data does not reflect after refresh..
仅添加AJAX调用实际上就是DWR(直接Web远程处理)调用.
Also just to add the AJAX call is actually a DWR (Direct Web Remoting) call.
请提出如何解决此问题的建议.
Please suggest how I can fix this issue.
推荐答案
在onbeforeunload事件中您只能做的 事情是询问用户是否要保存(这是因为某些页面可能会在onbeforeunload打开一个新窗口并对其进行垃圾邮件!)
the only thing you can do at onbeforeunload event is asking the user if he want's to save before (this is because some pages might open a new window at onbeforeunload and spam with it)!
var saved = false;
window.onbeforeunload = function () {
if (!saved) return "If you leave the page now your changes won't be saved.";
}
我认为最好的解决方案是将更改的数据存储在一个库中,当用户进入页面并保存数据时,该库将被删除
I think the best solution would be to store the changed data in a coockie which will be deleted when the user enters the page and the datas are saved
function getCookie(name) {
var a = document.cookie.split(';');
for(var i = 0; i < a.length; i++) {
var s = a[i];
while (s.charAt(0)==' ') s = s.substring(1,c.length);
if (s.indexOf((name + "=")) == 0) return s.substr((name + "=").length, s.length);
}
return null;
}
if (getCookie("save")) //save datas
这篇关于AJAX调用onbeforeunload以保存数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!