2011-05-05 126 views
0

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

我故意不從數據庫中讀取的評論,我只是將它張貼回來的頁面上。

+1

下投票,因爲無用的稱號。修改標題:) – James 2011-05-05 12:53:11

+3

你正在使用jQuery;你爲什麼不使用它的Ajax函數?順便說一句,可能的[XSS攻擊](http://en.wikipedia.org/wiki/XSS)發現:*在用戶數據輸出到網頁時,總是使用'htmlspecialchars'或'encodeurl'(取決於用例)。 – 2011-05-05 12:55:48

+0

順便說一句,你正在使用一個全局變量沒有任何必要('xml_http')。請不要!並使用'encodeURIComponent'來正確編碼查詢參數。也許你不應該使用GET請求來更新你的數據庫,GET請求應該是冪等的。 – 2011-05-05 13:23:06

回答

1

你或許應該追加只有當xml_http狀態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); 
} 
+0

...而當你在這裏,請擺脫全局變量並檢查'xml_http.status'。 – 2011-05-05 14:15:32

+0

一次一件;) – rciq 2011-05-05 14:18:07

+0

嗯,我們可以不同意這一點,但我認爲如果有人可以給出一個答案,告訴更多的問題提問者,但阻止他們從其他錯誤,應該這樣做。否則,Chibuzo很快就會回到一個問題,比如「爲什麼我的'responseText'是空的?」或者「爲什麼我的xml_http變量會改變?」 – 2011-05-05 14:22:06

相關問題