# 刷新/关闭页面之前发送请求
# 1. 说明
页面卸载(刷新/关闭)之前发送异步Ajax,很可能在它即将发送的时候,页面已经卸载了,从而导致发送取消或者发送失败。
解决方式如下:
window.onunload = e => {
// 方式 1: 发送同步 Ajax 请求
// 方式 2:使用 navigator.sendBeacon
};
// 返回值为 null | undefined 时,不会阻止页面卸载
window.onbeforeunload = function (e) {
// 阻止页面卸载
if (isUnsaved) {
return true;
}
return null;
}
# 2. 同步 Ajax 请求
chrome 里,同步请求不成功
jQuery.ajax({
url: 'http://localhost:5000/saveAll',
type: 'post',
data: JSON.stringify({ name: 'zhangsan' })
async: false,
contentType: 'application/json',
});
缺点:
- 阻塞页面卸载进程
# 3. navigator.sendBeacon
语法:
navigator.sendBeacon(url: string, data?: FormData | URLSearchParams): boolean
说明:
- 异步 POST 请求
- Content-Type: text/plain;charset=UTF-8
- 没有 response
示例:
navigator.sendBeacon('http://localhost:5000/saveStore', JSON.stringify({name: 'zhangsan'}))
# 4. fetch + keepalive
示例:
window.onunload = () => {
fetch(url, {
method: 'POST',
body: JSON.stringify({ name: "zhangsan" }),
headers: {
'content-type': 'application/json',
token: 'xxx',
},
keepalive: true,
})
}
# 5. 参考
- Sending AJAX Data when User Moves Away / Exits from Page (opens new window)
- 刷新/关闭页面之前发送请求 (opens new window)
- Navigator.sendBeacon() —— MDN (opens new window)
- Navigator.sendBeacon() —— 阮一峰 JavaScript 教程 (opens new window)
- How to receive data posted by "navigator.sendbeacon" on node.js server? (opens new window)
上一篇: 下一篇:
本章目录