【问题标题】:Jquery method executed several timejquery方法执行了几次
【发布时间】:2012-01-08 21:24:31
【问题描述】:

我正在尝试实现简单的 Comet 聊天示例,为此我实现了长轮询,它每 30 秒递归调用一次。

按下按钮时,我希望另一个 ajax 请求使用 POST 在服务器上发送新数据。

现在我只是提醒这个函数来触发点击事件

<script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
var polling = function poll(){
    $("#postMessage").click(function () {
    alert("request");
    });
    $.ajax({ dataType: 'json',url: "CometServlet", success: function(data){

            if (data !=null){
      $('#message').append(data.sender+" : " + data.message+"<br />");
            }
    }, complete: poll, timeout: 30000 });
}
$(document).ready(polling)

</script>

而我的 HTML 是这样的:

<div>
   <input type="button" id="postMessage" value="post Message">
</div>
<div id ="message" name="message"></div>

当我点击按钮时,我的警报会显示多次。为什么?我该如何解决?

【问题讨论】:

  • 你在等 30 秒吗?这不是timeout 的用途,如果那是您的想法的话。您确定额外的alerts 不只是因为您在每个 ajax 请求完成后立即调用 poll 吗?

标签: javascript jquery comet


【解决方案1】:

正如 Dave 提到的,这不是 timeout 选项的用途。尝试使用 setTimeout 代替。此外,您正在混合您的轮询逻辑和您的 click 处理程序(我认为)。以下是您将它们分开的方法:

function poll() {
    $.ajax({ 
        dataType: 'json',
        url: "CometServlet", 
        success: function(data){
            if (data !=null){
                $('#message').append(data.sender+" : " + data.message+"<br />");
            }
        },
        complete: function () {
            setTimeout(poll, 30000);
        }
    }); 
}

$(document).ready(function () {
    $("#postMessage").click(function () {
        alert("request");
    });

    poll();
});

示例: http://jsfiddle.net/VyGTh/

【讨论】:

    【解决方案2】:

    在每次 Ajax 调用后的代码中,您都将单击事件重新绑定到 #postMessage,这就是为什么您有几条警报消息的原因。您只需要在页面加载中绑定一次点击。您可以通过执行以下操作来修复它:

    <script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
    <script type="text/javascript">
    var polling = function poll(){
        $.ajax({ dataType: 'json',url: "CometServlet", 
               success: function(data){
                    if (data !=null){
                        $('#message').append(data.sender+" : " + data.message+"<br />");
                    }
               }, 
               complete: poll, 
               timeout: 30000 
        });
    }
    $(document).ready(function(){
        // Now Click only binds one time
        $("#postMessage").click(function () {
             alert("request");
        });
        polling();
    });
    
    </script>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-06
      • 1970-01-01
      • 2016-07-01
      相关资源
      最近更新 更多