阻止ajax重新获取数据

时间:2017-06-25 12:48:28

标签: jquery ajax

我正在构建像facebook这样的聊天系统。我想只将与特定用户关联的数据加载到弹出的用户Box中。就像facebook一样,当有人点击侧栏上用户列表上的用户名时会弹出一个聊天框(希望我有意义)。 一切正常,但是当我尝试获取数据时,数据会“重复”。 这是我打开聊天框和获取数据的代码。

$('li.user').click(function(){
    id = $(this).data('id');
    _status = $(this).data('status');
    username = $(this).data('username');
    _return = false;
    $('.chat .chat-boxes .box').each(function(){
      if($(this).data('id') == id){
        $(this).find('.box-footer .textarea').focus();
        _return = true;
     }
  });
  if (_return){
    return
  };
  $('.chat').find('.chat-boxes').append(box.format(id,_status,username));
    $('.box').each(function(){
        _boxBody = $(this).find('.box-body');
        _messagesBox = $(this).find('.messages');
        _id = $(this).data('id');
        _messagesBox.append('This is Box #'+_id);
        $.ajax({
            type: 'POST',
            url: base+'chat/getMessages.php',
            data: {'user2' : _id},
            cache: false,
            dataType: 'json',
            beforeSend: function(){$('.box-body-top').html('Loading...')},
            success: function(res){
                if(res.success){

                }
                else if(res.fail){

                }
            }
        });
    });
});

1 个答案:

答案 0 :(得分:0)

这可能是因为您在循环中包装了Ajax请求。

$(".box").each(function( index ) { ... });

如果存在多个附加了box类的元素,则这是您可以预期的请求数量。检查它的简单方法是在“网络”选项卡下的“开发人员工具”中查看已提出的请求数量。

你也应该考虑像这样使用套接字进行聊天系统。例如,看看socket.io。