您好我正在制作聊天应用程序。当用户滚动到顶部时,我想要显示的是显示历史/显示更多按钮,当我点击它时,应该批量加载更早的消息。由于多个用户可以聊天,我在存储获取的消息的最后一个id方面遇到问题。这是我的概念
当用户点击在线用户时,会从数据库中加载前10个消息。当用户滚动到顶部时,会出现更多按钮。如果他单击该按钮然后使用上次获取的行的id,我将再次获取下一个小于先前id的10行。但由于有多个用户,我需要存储不同的ID。我该怎么做这是我的jquery和php代码。
$('#m-'+id).scroll(function() {
var pos = $('#m-'+id).scrollTop();
if (pos == 0) {
$("#h2-"+id).after("<div id = 'showmore-"+id+"'>Show More</div>");
}
else{
$("#showmore-"+id).hide();
}
$("#showmore-"+id).click(function(){
$.ajax({
url: "loadmessage.php",
type: "POST",
data:{
'sender': sender,
'receiver': receiver,
},
//SELECT * FROM `messagse` WHERE ((sender_id = 1 AND receiver_id = 2) OR (sender_id = 1 AND receiver_id = 2)) AND (id < 36) order by id desc LIMIT 20
success: function(response){
var result = JSON.parse(response);
console.log("Result is " +result);
//result.sort();
for(var i = result.length-1; i >=0; i--){
$("#m-"+id).prepend('<p class = "shout_msg">' +result[i]+ '</p>');
}
}
});
})
});
PHP代码
<?php
if(isset($_REQUEST['sender']) AND isset($_REQUEST['receiver']) ){
$sender = $_REQUEST['sender'];
$receiver = $_REQUEST['receiver'];
require_once 'dc_chat.php';
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$result = $mysqli -> query("SELECT id from users where username LIKE '{$sender}'");
$row = mysqli_fetch_row($result);
$sender_id = $row[0];
$result = $mysqli -> query("SELECT id from users where username LIKE '{$receiver}'");
$row = mysqli_fetch_row($result);
$receiver_id = $row[0];
$sql = $mysqli -> query("SELECT username from users where id in (select sender_id from messagse where sender_id = $sender_id )");
$row = mysqli_fetch_row($sql);
$name = $row[0];
//$sql = $mysqli -> query("SELECT * from messagse where (sender_id = $sender_id AND receiver_id = $receiver_id) OR (sender_id = $receiver_id AND receiver_id = $sender_id) ");
$sql = $mysqli -> query("SELECT * FROM `messagse` WHERE (sender_id = $sender_id AND receiver_id = $receiver_id) OR (sender_id = $receiver_id AND receiver_id = $sender_id) order by id desc LIMIT 5");
$arr = array();
while($row = mysqli_fetch_array($sql)) {
$arr[] = $name." ". $row[3]." ".$row[4];
}
echo json_encode($arr);
}
?>
答案 0 :(得分:1)
但由于有多个用户,我需要存储不同的ID。我应该怎么做。
您应该按照要检索过去消息的用户的ID排序,而不是按表的ID排序。这样你可以将它限制在你想要的数字,例如限制5.然后你可以限制5,5等。