【问题标题】:Aborting AJAX request in long polling function在长轮询函数中中止 AJAX 请求
【发布时间】:2017-02-24 08:02:28
【问题描述】:

我正在实现一个可以监控后台作业的应用程序 (BLAST program)。

我希望当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); 
    }

如何取消轮询过程?任何建议将不胜感激。

【问题讨论】:

    标签: php jquery ajax bioinformatics long-polling


    【解决方案1】:

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

    根据您的要求,当结果显示“作业仍在运行”时,您应该从successhandler 调用doPoll

    【讨论】:

      【解决方案2】:

      尝试使用“clearTimeout()” 并且不要使用“完整”。

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

      【讨论】:

      • 感谢您的帮助,但上述方法无法在real time中显示日志消息,必须刷新页面才能看到已完成。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-28
      • 2013-06-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多