我使用以下代碼爲帖子添加評論並在不刷新頁面的情況下顯示該評論,但不知何故,它會顯示評論兩次而不是一次,但它只會在數據庫中保存一次。當我刷新頁面時,雖然它只顯示每個評論一次,所以我想問題是與「阿賈克斯響應」。這裏是代碼,謝謝你的幫助。當通過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