如何在没有取消的情况下在页面卸载时发送AJAX请求? [英] How to send an AJAX request on page unload without it cancelling?

查看:159
本文介绍了如何在没有取消的情况下在页面卸载时发送AJAX请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在卸载事件上发送 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请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆