我使用以下代码向帖子添加评论,并在不刷新页面的情况下显示评论,但不知何故,它显示了两次而不是一次评论,但它只在数据库中保存了一次。当我刷新页面时,它只显示每个评论一次,所以我想问题是与"ajax响应"。这是代码,谢谢你的帮助。
JavaScript:function addComment(pid) {
var url;
var comment = document.getElementById("comment").value;
xml_http = getXmlHttpObject();
if (xml_http == null) return alert("Your browser is too old to run this page!");
url = '../auth.php?comment=' + comment + '&pid=' + pid;
url += '&p=' + Math.random();
xml_http.onreadystatechange = commentStatus;
xml_http.open("GET", url, true);
xml_http.send(null);
}
function commentStatus() {
$("#comm").append(xml_http.responseText);
}
PHP: include_once('include/comment.php');
addComment($_GET['pid'], filter($_GET['comment']));
if(empty($_SESSION['pic'])) $pic = "images/silh.gif";
else $pic = "/profile/image.php/{$_SESSION['uname']}.{$_SESSION['pic']}?width=45&cropratio=1:1&image=/profile/pix/{$_SESSION['uname']}.{$_SESSION['pic']}";
echo "<div id='comments'>'n"
."<img src='{$pic}' align='left' style='padding-right:5px' />"
."<span id='bluetxt'>By {$_SESSION['uname']}</span><br />'n"
."<span>Posted Now</span>'n"
."<br /><br /><p style='clear:both'>{$_GET['comment']}</p>"
. "</div><br />'n";
我故意不读数据库中的评论,我只是把它贴回到页面上。
您可能应该只在xml_http state为4时追加注释。试试这样:
function addComment(pid) {
var url;
var comment = document.getElementById("comment").value;
var xml_http = getXmlHttpObject();
if (xml_http == null)
return alert("Your browser is too old to run this page!");
url = '../auth.php?comment=' + comment + '&pid=' + pid;
url += '&p=' + Math.random();
xml_http.onreadystatechange = function() {
if (xml_http.readyState==4) {
appendComment(xml_http.responseText);
}
};
xml_http.open("GET", url, true);
xml_http.send(null);
}
function appendComment(commentHTML) {
$("#comm").append(commentHTML);
}