与ajax聊天系统

时间:2016-08-06 06:51:57

标签: javascript php jquery ajax



<?php
        if (isset($_GET['conv_id'])) {
            $conversation = $_GET['conv_id'];
            $select_conv = "select * from messages where conv_id='$conversation'";
            $run_conv = mysqli_query($conn, $select_conv);
            while ($row_conv = mysqli_fetch_array($run_conv)) {
                $message_text = $row_conv['msg_topic'];
                $message_user_1=$row_conv['sender'];
                $message_user_2=$row_conv['receiver'];
                if($message_user_1==$user_email){
                echo "<div class='col-md-7' style='box-shadow: 0 0 3px #101010;border-radius: 4px;margin-bottom: 10px ;padding: 20px;float: right; background-color: #eeeeee'>$message_text</div>";
            }
                elseif ($message_user_1==$user_id){
                    echo "<div class='col-md-7' style='box-shadow: 0 0 3px #101010;border-radius: 4px;margin-bottom: 10px ;padding: 20px;float: right; background-color: #eeeeee'>$message_text</div>";
                }
else{
    echo "<div class='col-md-7' style='box-shadow: 0 0 3px #101010;border-radius: 4px;margin-bottom: 10px ;padding: 20px;float: left;background-color: #67b168'>$message_text</div>";
}
   }          
   echo "<div class='col_md-12'>
<form action='' method='post''>
<div class=\"form-group\">
  <label for=\"comment\"></label>
  <textarea class=\"form-control\" rows=\"5\" id=\"comment\" name='message_content' required></textarea>
</div>
<button type='submit' class='btn btn-default' name='send_msg'>Send</button>
</form>
<br>
<br>
<br>
</div>";
}
?>
    </div>
        <?php
if(isset($_POST['send_msg'])){
    $conv_id=$_GET['conv_id'];
    $message_file=$_POST['message_content'];
    $user_sender=$row['user_id'];
    $insert_message="insert into messages(conv_id,msg_topic,msg_date,sender,receiver,status) VALUES ('$conversation','$message_file',NOW(),'$user_email','','unread')";
    $run_message=mysqli_query($conn,$insert_message);
    if($run_message){  
        echo "<script>window.open('mymessages.php?conv_id=$conv_id','_self')</script>";
    }
}
?>
&#13;
&#13;
&#13;

我有一个PHP的聊天系统,使用外键来表示它们之间的关系 它的工作正常但速度慢,因为它需要重新加载页面而且不那么漂亮

我需要一个Ajax代码或Jquery或js代码来完成重新加载页面

像套接字编程一样

1 个答案:

答案 0 :(得分:1)

AJAX和套接字是两回事。

AJAX不像套接字那样提供持久性连接。如果您想在PHP中使用套接字创建聊天系统,请了解Websockets in PHP

如果您想使用 AJAX 构建聊天系统,您可以尝试长时间轮询行为,如持久性连接,但它不是那么流畅可靠作为套接字

套接字比建立聊天系统 AJAX 更受欢迎。