I want to ajax the collected access information to the server when the web page is closed. Is it practical? ?
The approximate code structure is as follows:
window.onbeforeunload=function(e){
visit_end=new Date();
visit_long=((visit_end.getTime()-visit_start.getTime())/1000).toFixed(1);
//此處省略以上采集的訪問信息
ajax_visit_info(); //在關(guān)閉網(wǎng)頁時(shí),調(diào)用ajax函數(shù)發(fā)送到后臺(tái)。
//return confirm('你真的要關(guān)閉嗎?'); //不想加上這個(gè),看起來不友好。
}
The question is, is it practical to use window.onbeforeunload to trigger ajax?
If the user's phone is stuck, or there is a problem with the network, will there be a high probability of missing the ajax trigger? ?
PS: I can test it with wamp.
歡迎選擇我的課程,讓我們一起見證您的進(jìn)步~~
This approach of yours will definitely lead to data loss, and once lost, it cannot be retrieved.
If the data is important, it is recommended to save a copy to the local cache and compare the timestamps every time it comes in. If the timestamp is newer than the last time it was submitted to the background, update the background data.
Doing this can avoid data loss caused by network problems.