我使用以下代码为帖子添加评论并在不刷新页面的情况下显示该评论,但不知何故,它会显示评论两次而不是一次,但它只会在数据库中保存一次。当我刷新页面时,虽然它只显示每个评论一次,所以我想问题是与“阿贾克斯响应”。这里是代码,谢谢你的帮助。当通过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";
我故意不从数据库中读取的评论,我只是将它张贴回来的页面上。
下投票,因为无用的称号。修改标题:) – James 2011-05-05 12:53:11
你正在使用jQuery;你为什么不使用它的Ajax函数?顺便说一句,可能的[XSS攻击](http://en.wikipedia.org/wiki/XSS)发现:*在用户数据输出到网页时,总是使用'htmlspecialchars'或'encodeurl'(取决于用例)。 – 2011-05-05 12:55:48
顺便说一句,你正在使用一个全局变量没有任何必要('xml_http')。请不要!并使用'encodeURIComponent'来正确编码查询参数。也许你不应该使用GET请求来更新你的数据库,GET请求应该是幂等的。 – 2011-05-05 13:23:06