2011-05-05 36 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

相关问题