AJAX call on onbeforeunload to save data

2019-08-28 02:48发布

问题:

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
   }

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..

Also just to add the AJAX call is actually a DWR (Direct Web Remoting) call.

Please suggest how I can fix this issue.

回答1:

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


回答2:

Mobile safari doesn't even support onbeforeunload at all.