@liayun
2016-05-14T14:36:24.000000Z
字数 14602
阅读 1891
知问前端
本文开始主要实现Ajax显示评论功能。
从question表中查出问题描述时,还要显示此问题共有多少条评论,所以得修改show_content.php为:
<?phprequire 'config.php';$query = mysql_query("SELECT (SELECT COUNT(*) FROM comment WHERE titleid = a.id) AS count,a.id,a.title,a.content,a.user,a.date FROM question a ORDER BY a.date DESC LIMIT 0,10") or die('SQL 错误!');$json = '';while (!!$row = mysql_fetch_array($query, MYSQL_ASSOC)) {//json格式转码foreach ( $row as $key => $value ) {$row[$key] = urlencode(str_replace("\n","", $value));$row[$key] = urlencode(str_replace("\t","", $value));}$json .= urldecode(json_encode($row)).',';//$json .= json_encode($row).','; //得到json格式//print_r($row); //以php数组的形式显示出来,javascript不能直接用,那么最好将其保存为json格式}//echo $json;echo '['.substr($json, 0, strlen($json) - 1).']'; //一个json数组,一个数组有3个对象,每个对象就是一个jsonmysql_close();?>
要点:
ajax远程加载comment表数据时,只加载一次。即$.ajax();只能在以下代码块中使用:
if(!$(".comment_list").eq(index).has("form").length) {$.ajax(...);}
而不能在以下代码块中使用:
if($(".comment_list").eq(index).is(":hidden")) {$(".comment_list").eq(index).show();//$.ajax(); //远程加载不应放在这儿}
顺序问题:
①评论列表显示在前,评论表单在后,所以得在ajax请求成功后,一起显现出来。
②评论表单生成后,然后依理才能提交评论表单到数据表。
所以以下jQuery代码就会有问题:
$.ajax({url : "show_content.php",type : "post",success : function(response, status, xhr) {var json = $.parseJSON(response);var html = "";var arr = [];var summary = [];$.each(json, function(index, value) {html += "<h4>" + value.user + " 发表于 " + value.date + "</h4><h3>"+value.title+"</h3><div class='editor'>" + value.content + "</div><div class='bottom'><span class='comment' data-id='" + value.id + "'>" + value.count + "条评论</span> <span class='up'>收起</span></div><hr noshade='noshade' size='1' /><div class='comment_list'></div>";});$(".content").append(html);$.each($(".editor"), function(index, value) {arr[index] = $(value).html();summary[index] = arr[index].substr(0, 200);if (summary[index].substring(199, 200) == "<") {summary[index] = replacePos(summary[index], 200, "");}if (summary[index].substring(198, 200) == "</") {summary[index] = replacePos(summary[index], 200, "");summary[index] = replacePos(summary[index], 199, "");}if(arr[index].length > 200) {summary[index] += '...<span class="down">显示全部</span>'; //一个大的问题,显示全部为动态添加进去,隐藏掉再添加进去的时候,click事件会失效$(value).html(summary[index]);}$(".bottom .up").hide();});//动态绑定,用委托绑定处理$.each($(".editor"), function(index, value) {$(this).on("click", ".down", function() {$(".editor").eq(index).html(arr[index]);$(this).hide();$(".bottom .up").eq(index).show();});});//统一处理$.each($(".bottom"), function(index, value) {$(this).on("click", ".up", function() {$(".editor").eq(index).html(summary[index]);$(this).hide();$(".editor .down").eq(index).show();});});$.each($(".bottom"), function(index, value) {$(this).on("click", ".comment", function() {var comment_this = this;if($.cookie("user")) {// 点击评论字样只允许评论表单出现一次if(!$(".comment_list").eq(index).has("form").length) {$.ajax({url : "show_comment.php",type : "post",beforeSend : function(jqXHR, settings) {$(".comment_list").eq(index).append("<dl class='comment_load'><dd>正在加载评论</dd></dl>");},success : function(response, status) {$(".comment_list").eq(index).find(".comment_load").hide();var json_comment = $.parseJSON(response);$.each(json_comment, function(index2, value) {$(".comment_list").eq(index).append("<dl class='comment_content'><dt>" + value.user + "</dt><dd>" + value.comment + "</dd><dd class='date'>" + value.date + "</dd></dl>");});$(".comment_list").eq(index).append("<form><dl class='comment_add'><dt><textarea name='comment'></textarea></dt><dd><input type='hidden' name='titleid' value='" + $(comment_this).attr("data-id") + "' /><input type='hidden' name='user' value='" + $.cookie("user") + "' /><input type='button' value='发表' /></dd></dl></form>");}});}if($(".comment_list").eq(index).is(":hidden")) {$(".comment_list").eq(index).show();} else {$(".comment_list").eq(index).hide();}//ajax远程加载,可能延迟1s、2s、3s//此时的表单在加载之前就已经执行了,会导致无法提交表单,而且按钮变成初始状态$(".comment_list").eq(index).find("input[type=button]").button().click(function() {//alert("123");//alert($(".comment_list").eq(index).find("form").find("textarea").val());var _this = this; // this指代按钮对象$(".comment_list").eq(index).find("form").ajaxSubmit({url : "add_comment.php",type : "post",beforeSubmit:function(formData,jqForm,options) {$("#loading").dialog("open");$(_this).button("disable"); //禁用发布按钮},success:function(responseText,statusText) {//alert(responseText); //新增成功,返回1if(responseText) {$(_this).button("enable");$("#loading").css("background","url(img/success.gif) no-repeat 20px center").html("数据新增成功...");setTimeout(function() {$("#loading").dialog("close");$(".comment_list").eq(index).find("form").resetForm(); //重置表单$("#loading").css("background","url(img/loading.gif) no-repeat 20px center").html("数据交互中...");}, 1000);}}});});} else {$("#error").dialog("open");setTimeout(function() {$("#error").dialog("close");$("#login").dialog("open");}, 1000);}});});}});
正确的jQuery代码为:
$.ajax({url : "show_content.php",type : "post",success : function(response, status, xhr) {var json = $.parseJSON(response);var html = "";var arr = [];var summary = [];$.each(json, function(index, value) {html += "<h4>" + value.user + " 发表于 " + value.date + "</h4><h3>"+value.title+"</h3><div class='editor'>" + value.content + "</div><div class='bottom'><span class='comment' data-id='" + value.id + "'>" + value.count + "条评论</span> <span class='up'>收起</span></div><hr noshade='noshade' size='1' /><div class='comment_list'></div>";});$(".content").append(html);$.each($(".editor"), function(index, value) {arr[index] = $(value).html();summary[index] = arr[index].substr(0, 200);if (summary[index].substring(199, 200) == "<") {summary[index] = replacePos(summary[index], 200, "");}if (summary[index].substring(198, 200) == "</") {summary[index] = replacePos(summary[index], 200, "");summary[index] = replacePos(summary[index], 199, "");}if(arr[index].length > 200) {summary[index] += '...<span class="down">显示全部</span>'; //一个大的问题,显示全部为动态添加进去,隐藏掉再添加进去的时候,click事件会失效$(value).html(summary[index]);}$(".bottom .up").hide();});//动态绑定,用委托绑定处理$.each($(".editor"), function(index, value) {$(this).on("click", ".down", function() {$(".editor").eq(index).html(arr[index]);$(this).hide();$(".bottom .up").eq(index).show();});});//统一处理$.each($(".bottom"), function(index, value) {$(this).on("click", ".up", function() {$(".editor").eq(index).html(summary[index]);$(this).hide();$(".editor .down").eq(index).show();});});$.each($(".bottom"), function(index, value) {$(this).on("click", ".comment", function() {var comment_this = this;if($.cookie("user")) {// 点击评论字样只允许评论表单出现一次if(!$(".comment_list").eq(index).has("form").length) {$.ajax({url : "show_comment.php",type : "post",beforeSend : function(jqXHR, settings) {$(".comment_list").eq(index).append("<dl class='comment_load'><dd>正在加载评论</dd></dl>");},success : function(response, status) {$(".comment_list").eq(index).find(".comment_load").hide();var json_comment = $.parseJSON(response);$.each(json_comment, function(index2, value) {$(".comment_list").eq(index).append("<dl class='comment_content'><dt>" + value.user + "</dt><dd>" + value.comment + "</dd><dd class='date'>" + value.date + "</dd></dl>");});$(".comment_list").eq(index).append("<form><dl class='comment_add'><dt><textarea name='comment'></textarea></dt><dd><input type='hidden' name='titleid' value='" + $(comment_this).attr("data-id") + "' /><input type='hidden' name='user' value='" + $.cookie("user") + "' /><input type='button' value='发表' /></dd></dl></form>");$(".comment_list").eq(index).find("input[type=button]").button().click(function() {//alert("123");//alert($(".comment_list").eq(index).find("form").find("textarea").val());var _this = this; // this指代按钮对象$(".comment_list").eq(index).find("form").ajaxSubmit({url : "add_comment.php",type : "post",beforeSubmit:function(formData,jqForm,options) {$("#loading").dialog("open");$(_this).button("disable"); //禁用发布按钮},success:function(responseText,statusText) {//alert(responseText); //新增成功,返回1if(responseText) {$(_this).button("enable");$("#loading").css("background","url(img/success.gif) no-repeat 20px center").html("数据新增成功...");setTimeout(function() {$("#loading").dialog("close");$(".comment_list").eq(index).find("form").resetForm(); //重置表单$("#loading").css("background","url(img/loading.gif) no-repeat 20px center").html("数据交互中...");}, 1000);}}});});}});}if($(".comment_list").eq(index).is(":hidden")) {$(".comment_list").eq(index).show();} else {$(".comment_list").eq(index).hide();}} else {$("#error").dialog("open");setTimeout(function() {$("#error").dialog("close");$("#login").dialog("open");}, 1000);}});});}});
可以对class='comment_load'修饰:
.content .comment_load dd {background: url(img/comment_load.gif) no-repeat 75px 45%;}
提交评论时,自动显示为在第一条的位置,实现方法即为在表单重置之前,将新的评论数据置为第一条目录,修改评论提交代码如下:
$(".comment_list").eq(index).find("input[type=button]").button().click(function() {//alert("123");//alert($(".comment_list").eq(index).find("form").find("textarea").val());var _this = this;$(".comment_list").eq(index).find("form").ajaxSubmit({url : "add_comment.php",type : "post",beforeSubmit:function(formData,jqForm,options) {$("#loading").dialog("open");$(_this).button("disable"); //禁用发布按钮},success:function(responseText,statusText) {//alert(responseText); //新增成功,返回1if(responseText) {$(_this).button("enable");$("#loading").css("background","url(img/success.gif) no-repeat 20px center").html("数据新增成功...");setTimeout(function() {var date = new Date();$("#loading").dialog("close");$(".comment_list").eq(index).prepend('<dl class="comment_content"><dt>' + $.cookie('user') + '</dt><dd>' + $('.comment_list').eq(index).find('textarea').val() + '</dd><dd>' + date.getFullYear() + '-' + (date.getMonth()+ 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds() + '</dd></dl>');$(".comment_list").eq(index).find("form").resetForm(); //重置表单$("#loading").css("background","url(img/loading.gif) no-repeat 20px center").html("数据交互中...");}, 1000);}}});});
以上代码还有问题:
问题一,无论点击哪个问题下的评论,均全部显示评论表comment中全部评论,而非显示对应问题下的评论。
问题二,即分页显示评论。
两者解决办法:
show_comment.php代码:
<?phpsleep(1);require 'config.php';$_sql = mysql_query("SELECT COUNT(*) AS count FROM comment WHERE titleid = '{$_POST['titleid']}'");$_result = mysql_fetch_array($_sql, MYSQL_ASSOC);//echo $_result['count'];$_pagesize = 2;$_count = ceil($_result['count'] / $_pagesize);//echo $_count;$_page = 1;if(!isset($_POST['page'])) {$_page = 1;} else {$_page = $_POST['page'];if($_page > $_count) {$_page = $_count;}}$_limit = ($_page - 1) * $_pagesize;$query = mysql_query("SELECT ({$_count}) AS count,titleid,comment,user,date FROM comment WHERE titleid = '{$_POST['titleid']}' ORDER BY date DESC LIMIT {$_limit},{$_pagesize}") or die('SQL 错误!');$json = '';while (!!$row = mysql_fetch_array($query, MYSQL_ASSOC)) {//json格式转码foreach ( $row as $key => $value ) {$row[$key] = urlencode(str_replace("\n","", $value));$row[$key] = urlencode(str_replace("\t","", $value));}$json .= urldecode(json_encode($row)).',';//$json .= json_encode($row).','; //得到json格式//print_r($row); //以php数组的形式显示出来,javascript不能直接用,那么最好将其保存为json格式}//echo $json;echo '['.substr($json, 0, strlen($json) - 1).']'; //一个json数组,一个数组有3个对象,每个对象就是一个jsonmysql_close();?>
jQuery代码如下:
$.each($(".bottom"), function(index, value) {$(this).on("click", ".comment", function() {var comment_this = this;//alert("123");if($.cookie("user")) {if(!$(".comment_list").eq(index).has("form").length) {$.ajax({url : "show_comment.php",type : "post",data : {titleid : $(comment_this).attr("data-id")},beforeSend : function(jqXHR, settings) {$(".comment_list").eq(index).append("<dl class='comment_load'><dd>正在加载评论</dd></dl>");},success : function(response, status) {$(".comment_list").eq(index).find(".comment_load").hide();// 初始加载第1页(每页2条评论)var json_comment = $.parseJSON(response);var count = 0;$.each(json_comment, function(index2, value) {//alert(value.count); //查询总页数count = value.count;$(".comment_list").eq(index).append("<dl class='comment_content'><dt>" + value.user + "</dt><dd>" + value.comment + "</dd><dd class='date'>" + value.date + "</dd></dl>");});$(".comment_list").eq(index).append("<dl><dd><span class='load_more'>加载更多评论</span></dd></dl>");// 有了"加载更多评论"按钮,则从第2页开始加载评论var page = 2;// 如果评论总数<=2,"加载更多评论"按钮的click事件销毁,并隐藏if (page > count) {//将click事件销毁掉,所以用on()事件$(".comment_list").eq(index).find(".load_more").off("click");$(".comment_list").eq(index).find(".load_more").hide();}$(".comment_list").eq(index).find(".load_more").button().on("click", function() {$(".comment_list").eq(index).find(".load_more").button("disable");$.ajax({url : "show_comment.php",type : "post",data : {titleid : $(comment_this).attr("data-id"),page : page //将要显示的第x页的x传递到服务器},beforeSend : function(jqXHR, settings) {$(".comment_list").eq(index).find(".load_more").html("<img src = 'img/more_load.gif' />");},success : function(response, status) {var json_comment_more = $.parseJSON(response);$.each(json_comment_more, function(index3, value) {$(".comment_list").eq(index).find(".comment_content").last().after("<dl class='comment_content'><dt>" + value.user + "</dt><dd>" + value.comment + "</dd><dd class='date'>" + value.date + "</dd></dl>");});$(".comment_list").eq(index).find(".load_more").button("enable");$(".comment_list").eq(index).find(".load_more").html("加载更多评论");page++; //不断显示下一页// 要查询的页数超过总页数,"加载更多评论"按钮的click事件销毁,并隐藏if (page > count) {//将click事件销毁掉,所以用on()事件$(".comment_list").eq(index).find(".load_more").off("click");$(".comment_list").eq(index).find(".load_more").hide();}}});});$(".comment_list").eq(index).append("<form><dl class='comment_add'><dt><textarea name='comment'></textarea></dt><dd><input type='hidden' name='titleid' value='" + $(comment_this).attr("data-id") + "' /><input type='hidden' name='user' value='" + $.cookie("user") + "' /><input type='button' value='发表' /></dd></dl></form>");// 所以type="button"的按钮的click事件要放置在表单生成之后$(".comment_list").eq(index).find("input[type=button]").button().click(function() {//alert("123");//alert($(".comment_list").eq(index).find("form").find("textarea").val());var _this = this;$(".comment_list").eq(index).find("form").ajaxSubmit({url : "add_comment.php",type : "post",beforeSubmit:function(formData,jqForm,options) {$("#loading").dialog("open");$(_this).button("disable"); //禁用发布按钮},success:function(responseText,statusText) {//alert(responseText); //新增成功,返回1if(responseText) {$(_this).button("enable");$("#loading").css("background","url(img/success.gif) no-repeat 20px center").html("数据新增成功...");setTimeout(function() {var date = new Date();$("#loading").dialog("close");$(".comment_list").eq(index).prepend('<dl class="comment_content"><dt>' + $.cookie('user') + '</dt><dd>' + $('.comment_list').eq(index).find('textarea').val() + '</dd><dd>' + date.getFullYear() + '-' + (date.getMonth()+ 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds() + '</dd></dl>');$(".comment_list").eq(index).find("form").resetForm(); //重置表单$("#loading").css("background","url(img/loading.gif) no-repeat 20px center").html("数据交互中...");}, 1000);}}});});}});}if($(".comment_list").eq(index).is(":hidden")) {$(".comment_list").eq(index).show();//$.ajax(); //远程加载不应放在这儿} else {$(".comment_list").eq(index).hide();}} else {$("#error").dialog("open");setTimeout(function() {$("#error").dialog("close");$("#login").dialog("open");}, 1000);}});});
添加css样式:
.content .load_more {width: 100%;margin: 10px 0 0 0;height: 30px;line-height: 30px;}.content .load_more img {padding: 5px 0 0 0;}