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(); //在关闭网页时,调用ajax函数发送到后台。
//return confirm('你真的要关闭吗?'); //不想加上这个,看起来不友好。
}
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.
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.