我有一个用ajax制作的反应系统。因此,当用户发布反应时,它由 ajax 请求处理并立即显示反应。现在,他将新反应(由 ajax 请求添加)放在初始加载的反应下。但是初始加载的反应是按 DESC 顺序从数据库中查询的,因此新反应必须放在初始加载的反应之上。我的代码:
HTML:
<div id="messages">
<?
$sql = "SELECT *
FROM items_comments, users
WHERE items_comments.item_id = '".$id."'
AND items_comments.user_id = users.user_id
ORDER BY comment_id DESC";
$result = $Db->sQuery($sql);
while($row = mysql_fetch_array($result)){
?>
<div id="com_loaded">
<div id="com_loaded_height"></div>
<div id="com_loaded_userpic"><a href="#" class="tooltip"><img src="<?=$row['user_pic']?>" class="img_poster" /><span><?=$row['user_name']?></span></a></div>
<div id="com_loaded_content">
<div id="com_loaded_poster"><a href="#"><?=$row['user_name']?></a></div>
<div id="com_loaded_text"><?=$row['comment_text']?></div>
</div>
<div id="com_loaded_divide"></div>
</div>
<?
}
?>
</div>
JS:
$(function() {
$(".submit-comment").click(function() {
var text = $(".txtinput").val();
var itemid = "<?=$id?>";
var userid = "<?=$_SESSION['user_id']?>";
var dataString = 'text=' + text + '&userid=' + userid + '&itemid=' + itemid;
if(text == '') {
$('#content_error1').fadeIn(250);
$('#content_error1').delay(1500).fadeOut(500);
} else {
$.ajax({
type: "POST",
url: "/ajax/comments.php",
data: dataString,
success: function(html){
$("#messages").append(html);
}
});
}
return false;
});
});
PHP 脚本 Ajax 调用
<? session_start();
require_once("../include/database.php");
$Db = new Database();
$text = $Db->escape($_POST['text']);
$itemid = $_POST['itemid'];
$userid = $_POST['userid'];
$date = date('Y-m-d');
$sql = "SELECT comment_id
FROM items_comments
ORDER BY comment_id DESC LIMIT 1";
$result = $Db->sQuery($sql);
$row = mysql_fetch_array($result);
$comment_id = ($row['comment_id'])+1;
$sql = "INSERT INTO items_comments (comment_id, item_id, user_id, comment_date, comment_text)
VALUES('$comment_id', '$itemid', '$userid', '$date', '$text')";
$Db->uidQuery($sql);
$sql = "SELECT *
FROM items_comments, users
WHERE items_comments.comment_id = '".$comment_id."'
AND items_comments.user_id = users.user_id
ORDER BY comment_date DESC";
$result = $Db->sQuery($sql);
$row = mysql_fetch_array($result);
$Db->closeConnection();
?>
<div id="com_loaded">
<div id="com_loaded_height"></div>
<div id="com_loaded_userpic"><a href="#" class="tooltip"><img src="<?=$row['user_pic']?>" class="img_poster" /><span><?=$row['user_name']?></span></a></div>
<div id="com_loaded_content">
<div id="com_loaded_poster"><a href="#"><?=$row['user_name']?></a></div>
<div id="com_loaded_text"><?=$row['comment_text']?></div>
</div>
<div id="com_loaded_divide"></div>
</div>