在长轮询函数中中止 AJAX 请求

Aborting AJAX request in long polling function

我正在实施一个能够监控后台作业的应用程序 ()。

我希望当PID等于0时,停止轮询过程。

但在我的长轮询示例中,轮询过程继续 运行 甚至使用 abort() 函数。

这个解决方案对我不起作用。

var poll_xhr;

    (function doPoll() {
        setTimeout(function() {
            poll_xhr = $.ajax({
                type: 'GET',
                url: 'longpoll.php',
                error: function (request, textStatus, errorThrown) {
                    displayError();
                },
                success: function(result) {
                    if (result == 0) {

                        // To kill the AJAX request (Not Working)
                        console.log("The process is not running.");
                        poll_xhr.abort();
                    }
                    else 
                        console.log(result);        
                },
                dataType: "json",
                complete: doPoll,
                timeout: 5000
            });
        })
    })();   

PHP 代码:

    $pid = $_SESSION['PID'];

    if(file_exists('/proc/'. $pid)){
        // $pid is running
        echo json_encode($pid);
    }
    else{ 
        $e = 0;
        echo json_encode($e); 
    }

如何取消投票过程?如有任何建议,我们将不胜感激。

尝试使用"clearTimeout()" 并且不要使用 "complete".

var poll_xhr;

(function doPoll() {
    var time=setTimeout(function() {
        poll_xhr = $.ajax({
            type: 'GET',
            url: 'break.php',
            error: function (request, textStatus, errorThrown) {
                //displayError();
                console.log(request, textStatus, errorThrown);
            },
            success: function(result) {
                if (result == 0) {

                    // To kill the AJAX request (Not Working)
                    console.log("The process is not running.");
                    //poll_xhr.abort();
                    clearTimeout(time);
                }
                else {
                    console.log(result);   
                    doPoll     
                }
            },
            dataType: "json",
            //complete: doPoll,
            timeout: 5000
        });
    })
})(); 

complete 上调用 doPoll 意味着它 总是 将被调用,无论结果和 xhr 的状态如何。

根据您的要求,当结果为 "job is still running"

时,您应该从 success 处理程序调用 doPoll