Cancel pending AJAX requests in PHP app?

前端 未结 3 1878
醉酒成梦
醉酒成梦 2021-01-07 23:53

I\'m having problems canceling my XHR requests when navigating between pages. I have a page that has 8 requests that get fired off. I cancel them on click of a link outside

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-08 00:36

    Probable causal chain

    1. the server does not realise the XHR requests are cancelled, and so the corresponding PHP processes keep running
    2. these PHP processes use sessions, and prevent concurrent access to this session until they terminate

    Possible solutions

    Adressing either of the above two points breaks the chain and may fix the problem:

    1. (a) ignore_user_abort is FALSE by default, but you could be using a non-standard setting. Change this setting back to FALSE in you php.ini or call ignore_user_abort(false) in the scripts that handle these interruptible requests.

    Drawback: the script just terminates. Any work in progress is dropped, possibly leaving the system in a dirty state.

    1. (b) By default, PHP will not detect that the user has aborted the connection until an attempt is made to send information to the client. Do echo something periodically during the course of your long-running script.

    Drawback: this dummy data might corrupt the normal output of your script. And here too, the script may leave the system in a dirty state.

    1. A PHP sessions is stored as a file on the server. On session_start(), the script opens the session file in write mode, effectively acquiring an exclusive lock on it. Subsequent requests that use the same session are put on hold until the lock is released. This happens when the script terminates, unless you close the session explicitely. Call session_write_close() or session_abort() as early as possible.

    Drawback: when closed, the session cannot be written anymore (unless you reopen the session, but this is somewhat inelegant a hack). Also the script does keep running, possibly wasting resources.

    I definitely recommend the last option.

提交回复
热议问题