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

后端 未结 2 1536
伪装坚强ぢ
伪装坚强ぢ 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');
        });
    });
    
    0 讨论(0)
  • 2021-02-14 23:17

    Doing standard ajax calls in a page unload handler is being actively disabled by browsers, because waiting for it to complete delays the next thing happening in the window (for instance, loading a new page). Although you can't do PUT with it, the replacement for synchronous ajax in unload handlers is sendBeacon. sendBeacon lets you send data to your server without holding up the page you're doing it in:

    window.addEventListener("unload", function() {
      navigator.sendBeacon("/log", yourDataHere);
    });
    

    The browser will send the data without preventing / delaying whatever is happening in the window (closing it, moving to a new paeg, etc.).

    Beacons are POSTs, not PUTs, but other than that it's exactly what you're looking for.

    0 讨论(0)
提交回复
热议问题