通过AJAX发布评论时显示两次,但在页面重新加载时只显示一次
Comments are shown twice when posted through AJAX, but appear only once on page reloads
我使用以下代码向帖子添加评论,并在不刷新页面的情况下显示评论,但不知何故,它显示了两次而不是一次评论,但它只在数据库中保存了一次。当我刷新页面时,它只显示每个评论一次,所以我想问题是与"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);
}
相关文章:
- 页面显示前加载Javascript警报
- 如何在发送ajax请求时显示进度加载程序
- 数据表 AJAX 筛选器重新加载数据
- Twitter引导选项卡显示页面加载时未触发事件
- 当另一个显示时加载HTML而不修改他
- Chart.js显示页面加载时的工具提示
- 当单击按钮时,隐藏已显示页面加载的段落
- 在加载数据之前显示Ionic加载
- 不显示 AJAX 加载程序
- AngularJS - 显示/隐藏加载器
- 如何在页面完成加载之前显示页面加载 html 文件
- 如何在新加载的页面上执行(下拉)操作
- 根据上一个选项卡的选择器重新加载选项卡
- 当网格视图设置为 true 时,Jqgrid 在 IE9 中显示“正在加载”
- 突出显示在加载表数据源时的工具提示
- 获得“中止,因为不接受 0”并使用反应热加载器重新加载整页
- ng-file-upload v12.0.1 - 在生成缩略图时显示临时“加载”图标
- 所有图像都显示在加载 JQuery 循环 2 插件时
- 显示离子加载器在NG重复渲染数据的过程之间
- 显示图像加载器,但不使用 ajax