问题
I have the situation that data needs to be reliably sent before browser window closes. My current implementation is to use a synchronous AJAX calls. However that's unlikely to work in the near future because the browsers are deprecating synchronous XHR calls according to https://xhr.spec.whatwg.org/#synchronous-flag
What I'm trying is to replace the ajax call with a fake "img" call, parameterize data to be sent and append it as the image's url query string. It seemed to work so far I tried. I don't really care about the server response so that as long as the request is made and pushed to the wire before browser window is unloaded.
My question is how reliable it is? Has anyone gotten any expeirences?
My other options is to keep the data in a cookie or webstorage and send them on the next request but that's based on the assumption that user will revisit which may not be true in my case.
Thanks.
回答1:
You can do it in unload event of window using ajax
you can refer the following links to know more about the problems and functionalities you need to take care of at this time in following links
Is there any possibility sending request before window closes
Is it reliable?
Is $(window).unload wait for AJAX call to finish before leaving a webpage
Hope this helps
回答2:
I think better use ajax request. I have no proof, but from my expirience, dom work slowly then js. For an example, when you do this one:
var div = document.createElement('div');
div.innerHTML = "mama";
div.className = "myDiv";
document.getElementById("myWrapper").appendChild(div);
var text = document.getElementByClassName('myDiv')[0].innerHTML;
sometimes you will get exception with message - can't read property innerHTML of undefined. But, if you will do that
setTimeout(function(){
var text = document.getElementByClassName('myDiv')[0].innerHTML;
}, 50);
it work allways fine. It's because dom still not updated. So, when you add image, dom may not be able to process it. And, when you send ajax request, it will be sended in any case I think.
来源:https://stackoverflow.com/questions/28219970/img-requests-before-windows-close