How to send AJAX request on window unload and NOT have to wait for a response

主宰稳场 提交于 2021-01-28 12:49:53

问题


I found that this works sporadically, but usually doesn't work at all.

$(window).unload(function()
{
    $.ajax
    ({
        url: "script.php",
        type: "POST",
        data: 
        { 
            value: value
        }
    });
});

Setting the async to false (i.e.'async' : false) does get around the problem and executes the php script every time. But depending on the script, it can freeze the browser up for a while.

Is there a good way of sending data to a php script and having the server execute it without the user waiting for a response?

EDIT - My understanding of client-server interaction is rusty, but it's not the request sending that's taking a long time, it's the processing of the data sent by the request. I'm wondering if that processing can occur without the user having to be on the page at all.


回答1:


You would need to accomplish this on the server side by closing the connection and then continuing to process the data. In php it would look something like this:

<?php
  header("Content-Length: 0");
  header("Connection: close");
  flush();

 //At this point the request is finished and you can continue to process the data. 
 //Keep in mind the connection is now closed and you can no longer return any information to the user.

?>

Note this isn't technically firing a background task so you should be fine doing this on a shared host. Just as long as it doesn't hang for an exceptionally long period of time.




回答2:


I wouldn't imagine so. The browser is being shut down thus it's trying to close all connections. I don't see how it would send a request without getting the user to wait. You're pretty much asking it to work in the background.

I would stick to async: false but perhaps notify the user with a Please wait... message or similar. Test in your target browsers too because it seems like a bit of a nuisance, not being able to close the browser/tab and waiting for an ajax call to finish.




回答3:


I have not tried, but maybe you can add a timeout (with a small value), or abort the request just after send it (with .abort() method).



来源:https://stackoverflow.com/questions/8023232/how-to-send-ajax-request-on-window-unload-and-not-have-to-wait-for-a-response

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!