问题描述
我正在尝试在unload
事件上发送PUT
请求,但是该请求始终被取消.
I'm trying to send a PUT
request on the unload
event, however the request is always cancelled.
这里的回答说这是不可能的:如何执行在页面上卸载ajax调用?
Answers here says it's not possible:How to perform an ajax call on page unload?
这里的答案表明有可能:如何页面卸载/离开时如何发送AJAX请求?
Answers here suggests it's possible:How do I send an AJAX request upon page unload / leaving?
我是否可以在卸载时发送AJAX请求,如果可以的话,如何在不取消的情况下进行发送.
Can I send an AJAX request on unload, if so how can I without being cancelled.
我不在乎响应,我不需要响应.只需向服务器发送一些信息,说该页面已关闭而没有保持活动状态.
I don't care about the response, I don't need a response. Just need to send some info to the server saying the page was closed without keep alive checks.
推荐答案
您需要做的就是使ajax调用同步.这样,浏览器将在关闭窗口/选项卡之前等待响应,并且不会被取消.
All you need to do is make the ajax call synchronous. That way the browser will wait for the response before closing the window/tab and it will not be cancelled.
$(window).unload(function(){
$.ajax({
type: 'PUT',
url: '/your_url.php',
async:false, //IMPORTANT, the call will be synchronous
data: {}
}).done(function(data) {
console.log('complete');
});
});
这篇关于如何在页面取消发送时发送AJAX PUT请求而不取消请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!