繁体   English   中英

jQuery Ajax停止长时间轮询

[英]jQuery Ajax stop long polling

我写了一个ping html版本,该版本出现在jQuery对话框中。

我希望当我关闭对话框时,再停止ping操作。

但是在我的版本中,警告“关闭”消息,然后再次继续执行ping操作。

<script type="text/javascript">
  var init = 1;
  var timestamp = null;
  var tag = $("<div></div>");
  function waitForMsg() {
    $.ajax({
      type: "GET",
      url: "/modules/ping2.php?host=localhost&tsp="+timestamp+"&init="+init,
      cache: false,
      success: function(data) {
        var json = eval('('+data+ ')');
        var str = json['out'].replace(/\n/g, "<br>");
        tag.html(str).dialog({
          title: 'Ping',
          modal: false,
          width: 480,
          height: 550,
          close: function() {
            alert('close');
          }
        }).dialog('open');
        timestamp = json["tsp"];
        init = 0;
        setTimeout("waitForMsg()", 1000);
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert("error: "+textStatus + " "+ errorThrown);
        setTimeout("waitForMsg()", 15000);
      }
    });
  }
  $(function() {
    $("#button").on('click', function() {
      waitForMsg();
    });
  });
</script>

我如何取消轮询?

如果要尽早停止ajax请求,请将ajax请求存储在变量中:

var request = $.ajax({
    /* ajax params */
});

您可以在需要时中止请求:

request.abort();

正如我在评论中指出的那样:

<script type="text/javascript">
  var timeout; // this is a variable the timout will be assigned to
  var init = 1;
  var timestamp = null;
  var tag = $("<div></div>");
  function waitForMsg() {
    $.ajax({
      type: "GET",
      url: "/modules/ping2.php?host=localhost&tsp="+timestamp+"&init="+init,
      cache: false,
      success: function(data) {
        var json = eval('('+data+ ')');
        var str = json['out'].replace(/\n/g, "<br>");
        tag.html(str).dialog({
          title: 'Ping',
          modal: false,
          width: 480,
          height: 550,
          close: function() {
            alert('close');
            clearTimeout(timeout); // here we clear the timeout
          }
        }).dialog('open');
        timestamp = json["tsp"];
        init = 0;
        timeout = setTimeout("waitForMsg()", 1000); // here we assign the timout
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert("error: "+textStatus + " "+ errorThrown);
        setTimeout("waitForMsg()", 15000);
      }
    });
  }
  $(function() {
    $("#button").on('click', function() {
      waitForMsg();
    });
  });
</script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM