@liayun
2016-05-14T10:08:46.000000Z
字数 8500
阅读 1734
知问前端
本文开始主要实现Ajax评论功能,包括Ajax显示评论,提交评论,加载更多等等操作。
首先,HTML结构要组织好,此文关注的HMTL代码如下:
<div id="main"><div class="main_left"><div id="tabs"><ul><li><a href="tab1.html">tab1</a></li><li><a href="tab2.html">tab2</a></li><li><a href="tab3.html">tab3</a></li></ul></div><div class="content"><h4>liayun 发表于 2016-05-07</h4><h3>外貌和魅力方面被打击该如何调整心态?</h3><div class="editor">问题描述内容...</div><div class="bottom"><span class="comment">0条评论</span><span class="down">显示全部</span><span class="up">收起</span></div><hr noshade="noshade" size="1" /><!-- 评论列表区 --><div class='comment_list'><!-- 显示的评论列表 --><dl class='comment_content'><!-- 第一条评论 --><dt>liayun</dt><dd>如果祖辈的资源和条件不是因为你自己想用而用的话,这会转变成一种巨大的压力。</dd><dd class='date'>2016-05-13</dd><!-- 第二条评论 --><dt>liayun</dt><dd>如果祖辈的资源和条件不是因为你自己想用而用的话,这会转变成一种巨大的压力。</dd><dd class='date'>2016-05-13</dd><!-- 第三条评论 --><dt>liayun</dt><dd>如果祖辈的资源和条件不是因为你自己想用而用的话,这会转变成一种巨大的压力。</dd><dd class='date'>2016-05-13</dd></dl><!-- 评论表单 --><form><dl class='comment_add'><dt><textarea name='comment'></textarea></dt><dd><input type='button' value='发表' /></dd></dl></form></div></div></div><div class="main_right"><div id="accordion"><h3>菜单1</h3><div><p>内容1</p><p>内容1</p></div><h3>菜单2</h3><div>内容2</div><h3>菜单3</h3><div>内容3</div></div></div></div>
进一步,只关注评论列表class='comment_list'的<div>。
CSS修饰样式如下:
.content .comment {color:#369;cursor:pointer;}.content .comment_list {border: 1px solid #ccc;border-radius: 4px;padding: 5px 10px;display: none; /* 初始评论列表区隐藏 */}.content .comment_list dl {margin: 0;padding: 3px 0 5px 0;}.content .comment_list dl dt {margin: 0;padding: 5px 0 0 0;color: #369;}.content .comment_list dl dd {margin: 0;padding: 0;color: #333;line-height: 180%;}.content .comment_list dl dd.date {color: #666;}.content .comment_list dl.comment_content {border-bottom: 1px solid #ccc;}.content .comment_add {text-align: right;}.content .comment_add textarea {width: 98%;border: 1px solid #ccc;border-radius: 4px;background: #fff;padding: 5px;font-size: 12px;color: #666;resize: none;}.content .comment_add input {cursor:pointer;}
此刻,添加完CSS样式之后,HTML代码我们实际写为:
<div id="main"><div class="main_left"><div id="tabs"><ul><li><a href="tab1.html">tab1</a></li><li><a href="tab2.html">tab2</a></li><li><a href="tab3.html">tab3</a></li></ul></div><div class="content"></div></div><div class="main_right"><div id="accordion"><h3>菜单1</h3><div><p>内容1</p><p>内容1</p></div><h3>菜单2</h3><div>内容2</div><h3>菜单3</h3><div>内容3</div></div></div></div>
接下来,实现点击评论字样展开评论表单的功能:
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'>0条评论</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() {if($.cookie("user")) {// 点击评论字样只允许评论表单出现一次if(!$(".comment_list").eq(index).has("form").length) {$(".comment_list").eq(index).append("<form><dl class='comment_add'><dt><textarea name='comment'></textarea></dt><dd><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();}} else {$("#error").dialog("open");setTimeout(function() {$("#error").dialog("close");$("#login").dialog("open");}, 1000);}});});}});
创建数据表:comment,字段分别为:id、titleid、user、comment、date等字段。
comment表的结构如图:
add_comment.php:
<?phpsleep(1);require 'config.php';$query = "INSERT INTO comment (titleid, comment, user, date) VALUES ('{$_POST['titleid']}', '{$_POST['comment']}', '{$_POST['user']}', NOW())";mysql_query($query) or die('新增失败!'.mysql_error());echo mysql_affected_rows();mysql_close();?>
由于要上传titleid,所以还需从数据表content表中查出id,即show_content.php修改为:
<?phprequire 'config.php';$query = mysql_query("SELECT id,title,content,user,date FROM question ORDER BY date DESC LIMIT 0,5") 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();?>
此时,0条评论字样增加一个自定义属性data-id,第一次碰到,要注意,所以此时变为:
<span class='comment' data-id='" + value.id + "'>0条评论</span>
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 + "'>0条评论</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() {if($.cookie("user")) {// 点击评论字样只允许评论表单出现一次if(!$(".comment_list").eq(index).has("form").length) {$(".comment_list").eq(index).append("<form><dl class='comment_add'><dt><textarea name='comment'></textarea></dt><dd><input type='hidden' name='titleid' value='" + $(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();}$(".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);}});//$(".comment_add").eq(index).find("input").button();//$(".comment_list").eq(index).find("input[type=button]").button(); //按钮样式不会发生改变,所以应紧紧接着表单生成,并显示之后});}});