微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

JQuery和PHP独特的聊天窗口为每个用户和数据库保存了聊天记录

我设法根据点击的用户创建唯一打开的聊天窗口但我不能在任何聊天窗口上发送消息,除了第一个.

我想要实现这个目标:

我正在努力实现那个^

这是我到目前为止:

<script> //CHAT SYstem
    function chatWith(id,status,username){ 
        $("#chats").append('<div class="chat_window" id="chat_'+id+'"><div class="chat_top"><span class="chat_username">'+status+username+'</span><span class="chat_x"><a href="javascript:void(0)" onclick="minChat('+id+')">-</a> <a href="javascript:void(0)" onclick="closeChat('+id+')">X</a>  </span> </div>  <div class="chat_content"></div> <form method="post" name="chat" action=""> <textarea class="chat_text" maxlength="200" name="chat_text" id="chat_text_'+id+'" placeholder="Start typing..."></textarea> </form> </div></dv>'); 
        $("#chat_"+id).slidetoggle("fast");             
    } 

    //send messages
    var user_id = '<?PHP echo $session_user_id;?>';
    var auto_refresh = setInterval(function () {
        var b = $("#chat_"+user_id+":last").attr("id");     
        $.getJSON("chat.PHP?user_id="+user_id,function(data){
            $.each(data.posts,function(i,data) {               
                if(b != data.id)  { 
                    var div_data="<span id='"+data.id+"'>"+data.user_id+": "+data.msg+"</span>";                        
                    $(div_data).appendTo("#chat_"+user_id);
                }
            });
        });
    },2000);   
    $(document).ready(function(){
        $(document).keypress(function(e) {
            if(e.which == 13) {
                var Boxval = $(".chat_text").val();                 
                var user_id = '<?PHP echo $session_user_id;?>';
                var dataString = 'user_id='+ user_id + '&msg=' + Boxval;

                if(Boxval.length > 0) { 
                    $.ajax({
                        type: "POST",url: "chat.PHP",data: dataString,cache: false,success: function(html){                     
                            $(".chat_content").append(html);
                            $(".chat_text").val('');
                            $(".chat_text").focus();
                            $(".chat_content").animate({scrollTop: $(".chat_text").offset().top},500);
                        }
                    });             
                }
                return false;
            }
        });
    });

</script>

这是我的chat.PHP

if($_POST){
    $user_id = $_POST['user_id'];
    $msg = $_POST['msg'];

    MysqL_query("INSERT INTO chat(user_id,msg) VALUES ('$user_id','$msg')");

    $chat_results = MysqL_fetch_assoc(MysqL_query("SELECT * FROM `users` WHERE user_id='".$user_id."' LIMIT 1"));

    echo '<span style="font-size:0.9em;font-weight:bold;">'.$chat_results['username'].'</span>: <span style="font-size:0.9em;">'.$msg.'</span><br>';
}
if($_GET['user_id']){
    $user_id=$_GET['user_id'];
    $row=MysqL_fetch_array(MysqL_query("SELECT * FROM chat order by id desc limit 1"));
    $user_idx = $row['user_id'];
    $id = $row['id'];
    $msg = $row['msg'];
    if($user_idx != $user_id){
        echo '{"posts": [{  "id":"'.$id.'","user_id":"'.$user_idx.'","msg":"'.$msg.'" },]}';
    } 
}

这一切都打开了:

<div id="chats"> 

</div>

真的很感激任何帮助,现在已经打破了我好几个星期!

解决方法

你的问题在这里
var Boxval = $(".chat_text").val(); //<-- here it is                
            ...

            $(".chat_content").append(html);//<-- here it is  
            $(".chat_text").val('');//<-- here it is  
            $(".chat_text").focus();//<-- here it is  
            $(".chat_content").animate({scrollTop: $(".chat_text").offset().top},500);//<-- here it is

很明显,每个“聊天窗口”都有类“.chat_content”,“.chat_text”

那么你的js怎么能猜出哪一个是正确的呢?所以它显然只需要第一次出现的解释它只能在第一个窗口中起作用.

所以有1000种方式去罗马

我会推荐一个

在第一次纠正chatWith追加,最后

</dv>

是不必要的,必须删除

function chatWith(id,username){ 
    $("#chats").append('<div class="chat_window" id="chat_'+id+'"><div class="chat_top"><span class="chat_username">'+status+username+'</span><span class="chat_x"><a href="javascript:void(0)" onclick="minChat('+id+')">-</a> <a href="javascript:void(0)" onclick="closeChat('+id+')">X</a>  </span> </div>  <div class="chat_content"></div> <form method="post" name="chat" action=""> <textarea class="chat_text" maxlength="200" name="chat_text" id="chat_text_'+id+'" placeholder="Start typing..."></textarea> </form> </div>'); 
    $("#chat_"+id).slidetoggle("fast");             
}

那么你首先需要发送正确的值
你宁愿将按键委托给textareas,而不是像文件一样

$(document).on('keypress','.chat_text',function(e){ //<-- heres the event context passed as argument Now,just like you did (copy) yourself
  if(e.which == 13) {
    //wow,Now you have the correct textarea in this-context 
    //dont loose it 
    $current=$(this);
    var Boxval = $current.val();
    // and prove it!!
    console.log("the currently entered text is: "+Boxval);

    //should be correct,Now the requesting and appending part
    var user_id = '<?PHP echo $session_user_id;?>';
    var dataString = 'user_id='+ user_id + '&msg=' + Boxval;
    // prove it ! 
    console.log("dataString is: "+dataString+" and therefore correct");
    if(Boxval.length > 0) { 
       $.ajax({
            type: "POST",success: function(html){  
                    // better prove if user_id is really correct:
                    console.log("Box that will be filled is from user id: "+html.user_id);   
                    // Now you have the userid on which you can match to the 
                    // id of the generated chat windows like in answer above mentioned                   
                    $BoxToBeFilled=$("#chat_" + html.user_id);

                    $BoxToBeFilled.append(Boxval);
                    $BoxToBeFilled.find('textarea').val('').focus();
                    $BoxToBeFilled.children(".chat_content").animate({scrollTop: $(this).find(".chat_text").offset().top},500);
            }
        });             
    }
 } 
});

你去吧

原文地址:https://www.jb51.cc/jquery/178357.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐