javascript 如何使用ajax、jquery和php制作像facebook这样的聊天框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21152828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to make a chat box like facebook using ajax, jquery and php
提问by
See I have made almost the chat box with only 2 problems. I don't know how to solve them. I'm trying hopeless methods to make it correct but it just won't work. I will explain my code below... Here is the HTML part where chat box, chat text area and chat members are present. what I'm trying to do is that there is some chat members list on the left side. If I click on any of the chat member's name, the chat related to that person opens up. That is it is a one to one chat between the logged in user and one of the chat members. Chat members are basically the fiends of the logged in user.
看我已经制作了几乎只有 2 个问题的聊天框。我不知道如何解决它们。我正在尝试无望的方法来使其正确,但它不起作用。我将在下面解释我的代码......这是聊天框、聊天文本区域和聊天成员存在的 HTML 部分。我想要做的是在左侧有一些聊天成员列表。如果我单击任何聊天成员的姓名,就会打开与该人相关的聊天。也就是说,登录用户和其中一位聊天成员之间是一对一的聊天。聊天成员基本上是登录用户的恶魔。
<div id="chat_box">
</div>
<div id="input_chat">
<input type="text" id="input_ur_chat" placeholder="Press ENTER After Writing" name="chat_msg" />
</div>
<div style="background-color:black; position:absolute; height:100%; width:25%; opacity:0.8;">
<div id="chat_members">
<p id='1' class='chat_members_list'>anurag</p>
<p id='2' class='chat_members_list'>golu</p>
<p id='3' class='chat_members_list'>akash</p>
</div>
</div>
In the div chat_members, id represents the userid of that person which is the value of the attribute to uniquely identify that user in the database.
在 div chat_members 中,id 表示该人的用户 ID,它是在数据库中唯一标识该用户的属性值。
Now my ajax and jquery code for the chat box is as follows:
现在我的聊天框ajax和jquery代码如下:
<script>
$(document).ready(function()
{
$('.chat_members_list').click(function()
{
var chatmember = $(this).attr('id');
var iusername = "<?php echo $usname; ?>"; //the current logged in user
//alert(chatmember);
$(".chat_members_list").css("color","white");
$("#" + chatmember).css("color","lightskyblue");
load_data = {'fetch':1, 'username1':iusername, 'receivername1':chatmember};
$("#chat_box").html("<img src='images/loader3.gif' />loading...");
window.setInterval(function()
{
$.post('shout.php', load_data, function(data)
{
$('#chat_box').html(data);
var scrolltoh = $('#chat_box')[0].scrollHeight;
$('#chat_box').scrollTop(scrolltoh);
});
}, 1000);
//method to trigger when user hits enter key
$("#input_ur_chat").keyup(function(evt)
{
if(evt.keyCode == 13)
{
var imessage = $('#input_ur_chat').val();
alert(iusername);
alert(imessage);
alert(chatmember);
post_data = {'username':iusername, 'message':imessage, 'receivername':chatmember};
//send data to "shout.php" using jQuery $.post()
$.post('shout.php', post_data, function(data)
{
//append data into messagebox with jQuery fade effect!
$(data).hide().appendTo('#chat_box').fadeIn();
//keep scrolled to bottom of chat!
var scrolltoh = $('#chat_box')[0].scrollHeight;
$('#chat_box').scrollTop(scrolltoh);
//reset value of message box
$('#input_ur_chat').val('');
}).fail(function(err)
{
//alert HTTP server error
alert(err.statusText);
});
}
});
});
});
And here is my php code,
这是我的 php 代码,
<?php
session_start();
$usname=$_SESSION['username'];
$db_username = 'root';
$db_password = '*********';
$db_name = 'anurag';
$db_host = 'localhost';
if($_POST)
{
$sql_con = mysqli_connect($db_host, $db_username, $db_password,$db_name)or die('could not connect to database');
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
die();
}
if(isset($_POST["message"]) && strlen($_POST["message"])>0)
{
//sanitize user name and message received from chat box
//You can replace username with registerd username, if only registered users are allowed.
$username = filter_var(trim($_POST["username"]),FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
$message = filter_var(trim($_POST["message"]),FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
$user_ip = $_SERVER['REMOTE_ADDR'];
$r_msg = $_POST['receivername'];
$result1 = mysqli_query($sql_con,"SELECT uid FROM members WHERE username='$usname' ");
$row1=mysqli_fetch_array($result1);
$asd=$row1['uid'];
//insert new message in db
if(mysqli_query($sql_con,"INSERT INTO friends_chat values('$asd','$r_msg','$message',NOW())"))
{
$msg_time = date('h:i A M d',time()); // current time
echo '<div class="shout_msg"><time>'.$msg_time.'</time><span class="username">'.$username.'</span><span class="message">'.$message.'</span></div>';
}
}
elseif($_POST["fetch"]==1)
{
$username1 = filter_var(trim($_POST["username1"]),FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
$r_msg1 = $_POST['receivername1'];
$result12 = mysqli_query($sql_con,"SELECT uid FROM members WHERE username='$usname' ");
$row12=mysqli_fetch_array($result12);
$asd1=$row12['uid'];
$results = mysqli_query($sql_con,"SELECT s_msg,r_msg,message,time_msg
FROM friends_chat
WHERE s_msg='$asd1'
AND r_msg='$r_msg1'
");
while($row = mysqli_fetch_array($results))
{
$msg_time1 = date('h:i A M d',strtotime($row["time_msg"])); //message posted time
echo '<div class="shout_msg1"><time>'.$msg_time1.' : '.'</time><span class="username1">'.$row["s_msg"].' := '.'</span> <span class="message1">'.$row["message"].'</span></div>';
}
}
else
{
header('HTTP/1.1 500 Are you kiddin me?');
exit();
}
}
?>
Now I'll tell you my problems.
现在我会告诉你我的问题。
First, when I click on a chat member, the chat related to that member is opening. When I input any value in the input field, only one row is inserted. Even after refreshing the page and trying again, only one row is inserting. The problem might be the click event in the starting of the script. As the ajax request will be initiated only when the click event had occurred. This the problem. I want to only one click event for each member and then they can chat. There is one more problem in this that when I refresh the page and again start the chat with one of the members with that click event since 1 row was inserted before the refresh, no new rows are inserting. I don't know the root of this problem. I hope u understand my problem now. If u need any more info please tell me and help me.
首先,当我点击一个聊天成员时,与该成员相关的聊天正在打开。当我在输入字段中输入任何值时,只会插入一行。即使在刷新页面并重试后,也只插入了一行。问题可能是脚本开始时的点击事件。因为只有当点击事件发生时才会启动ajax请求。这就是问题。我只想为每个成员点击一个事件,然后他们就可以聊天了。还有一个问题,当我刷新页面并再次开始与具有该单击事件的成员之一聊天时,因为在刷新之前插入了 1 行,没有插入新行。我不知道这个问题的根源。我希望你现在明白我的问题。如果您需要更多信息,请告诉我并帮助我。
回答by Ikelie Cyril
I think the keyup event should be separated from the click event. This should be a separate event
我认为 keyup 事件应该与 click 事件分开。这应该是一个单独的事件
$('.chat_members_list').click(function(){
//code
});
While this should be a separate event too
虽然这也应该是一个单独的事件
$("#input_ur_chat").keyup(function(evt){
//code
});
回答by Martijn
You might want to check out sockets, like Socket.js. It's a bit more difficult, but this is what you are looking for. A socket is a bit more complex, but super fast. You could use AJAX for this, but AJAX is very slow compared to a socket.
您可能想查看套接字,例如Socket.js。这有点困难,但这就是你正在寻找的。套接字有点复杂,但速度非常快。您可以为此使用 AJAX,但与套接字相比,AJAX 非常慢。
In the onMessageevent you broadcastthe message to all connected users, and with the onConnectand onDisconnectyou broadcasta list of connected users to everybody.
在的onMessage事件中,你的广播消息给所有连接的用户,并与为onConnect和onDisconnect你广播连接的用户每个人的列表。