用Ajax和JQuery构建一个评论系统,我想在添加评论后重新加载评论所在的div。它可以正常开机自检。这就是我到目前为止所拥有的。
函数getComments查询数据库并生成html
$.ajax({
type: "POST",
url: "post_comment.php",
data: dataString,
cache: false,
success: function(html){
????????? What should go here... it is a div with id#commentBody
}
<div id="commentBody">
<ul>
<?php
$q = "SELECT * FROM comment WHERE parent_id = 0 AND idpost = $postID";
$r = mysql_query($q);
while($row = mysql_fetch_assoc($r)):
getComments($row,$postID,$custID);
endwhile;
?>
</ul>
</div> 发布于 2011-02-27 05:52:28
当你发布它时,你应该从你的服务器端脚本返回你想要的数据。然后,您可以使用.html() jQuery函数来更新您的div。
所以,就像:
$('#commentBody').html(html);您也可以只返回最新的注释(也可以作为JSON对象),然后使用.append()方法将其添加到#commentBody中。
我将创建一个具有status属性和data属性的JSON对象。当status为-1 (或其他值)时,添加注释时出现错误,您可以在data属性中添加一条消息。当status为0时,它是成功的,最新的注释信息将在data属性中可用。
示例
PHP
//Check postback variables, add comment and retrieve
// comment information (such as ID) if necessary
if (postedsuccessfully) {
$ary = array("status" => 0,
"data" => array("id" => $commentidvar,
"user" => $commentuser,
"text" => $comment)
);
echo json_encode($ary);
} else {
$ary = array("status" => -1,
"data" => "There was a problem adding your comment.");
echo json_encode($ary);
}JavaScript
success: function(json){
if (json.status == 0) {
$mydiv = $('<div>');//construct your comment div using json.data.id,
//json.data.user, and json.data.text
$('#commentBody').append($mydiv);
} else {
alert(json.data);
}
}发布于 2011-02-27 05:50:28
由于您重新生成了整个div,因此我将使用replaceWith。
$('#commentBody').replaceWith(html);
https://stackoverflow.com/questions/5129955
复制相似问题