How to send an AJAX PUT request on page unload without it cancelling?

后端 未结 2 1525
伪装坚强ぢ
伪装坚强ぢ 2021-02-14 22:09

I\'m trying to send a PUT request on the unload event, however the request is always cancelled.

Answers here says it\'s not possible:How to per

2条回答
  •  借酒劲吻你
    2021-02-14 23:17

    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');
        });
    });
    

提交回复
热议问题