jQuery Ajax停止长轮询

时间:2014-04-10 18:10:57

标签: javascript jquery ajax ping

我写了一个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>

如何取消投票?

2 个答案:

答案 0 :(得分:2)

如果您想提前停止ajax请求,请将ajax请求存储在变量中:

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

当你需要这样的时候,你可以中止请求:

request.abort();

答案 1 :(得分:2)

我在评论中指出:

<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>