[关闭]
@liayun 2016-05-14T10:08:46.000000Z 字数 8500 阅读 1386

知问前端--Ajax提交评论

知问前端


本文开始主要实现Ajax评论功能,包括Ajax显示评论,提交评论,加载更多等等操作。

一、显示评论表单

首先,HTML结构要组织好,此文关注的HMTL代码如下:

  1. <div id="main">
  2. <div class="main_left">
  3. <div id="tabs">
  4. <ul>
  5. <li><a href="tab1.html">tab1</a></li>
  6. <li><a href="tab2.html">tab2</a></li>
  7. <li><a href="tab3.html">tab3</a></li>
  8. </ul>
  9. </div>
  10. <div class="content">
  11. <h4>liayun 发表于 2016-05-07</h4>
  12. <h3>外貌和魅力方面被打击该如何调整心态?</h3>
  13. <div class="editor">
  14. 问题描述内容...
  15. </div>
  16. <div class="bottom">
  17. <span class="comment">0条评论</span>
  18. <span class="down">显示全部</span>
  19. <span class="up">收起</span>
  20. </div>
  21. <hr noshade="noshade" size="1" />
  22. <!-- 评论列表区 -->
  23. <div class='comment_list'>
  24. <!-- 显示的评论列表 -->
  25. <dl class='comment_content'>
  26. <!-- 第一条评论 -->
  27. <dt>liayun</dt>
  28. <dd>如果祖辈的资源和条件不是因为你自己想用而用的话,这会转变成一种巨大的压力。</dd>
  29. <dd class='date'>2016-05-13</dd>
  30. <!-- 第二条评论 -->
  31. <dt>liayun</dt>
  32. <dd>如果祖辈的资源和条件不是因为你自己想用而用的话,这会转变成一种巨大的压力。</dd>
  33. <dd class='date'>2016-05-13</dd>
  34. <!-- 第三条评论 -->
  35. <dt>liayun</dt>
  36. <dd>如果祖辈的资源和条件不是因为你自己想用而用的话,这会转变成一种巨大的压力。</dd>
  37. <dd class='date'>2016-05-13</dd>
  38. </dl>
  39. <!-- 评论表单 -->
  40. <form>
  41. <dl class='comment_add'>
  42. <dt><textarea name='comment'></textarea></dt>
  43. <dd><input type='button' value='发表' /></dd>
  44. </dl>
  45. </form>
  46. </div>
  47. </div>
  48. </div>
  49. <div class="main_right">
  50. <div id="accordion">
  51. <h3>菜单1</h3>
  52. <div><p>内容1</p><p>内容1</p></div>
  53. <h3>菜单2</h3>
  54. <div>内容2</div>
  55. <h3>菜单3</h3>
  56. <div>内容3</div>
  57. </div>
  58. </div>
  59. </div>

进一步,只关注评论列表class='comment_list'<div>
CSS修饰样式如下:

  1. .content .comment {
  2. color:#369;
  3. cursor:pointer;
  4. }
  5. .content .comment_list {
  6. border: 1px solid #ccc;
  7. border-radius: 4px;
  8. padding: 5px 10px;
  9. display: none; /* 初始评论列表区隐藏 */
  10. }
  11. .content .comment_list dl {
  12. margin: 0;
  13. padding: 3px 0 5px 0;
  14. }
  15. .content .comment_list dl dt {
  16. margin: 0;
  17. padding: 5px 0 0 0;
  18. color: #369;
  19. }
  20. .content .comment_list dl dd {
  21. margin: 0;
  22. padding: 0;
  23. color: #333;
  24. line-height: 180%;
  25. }
  26. .content .comment_list dl dd.date {
  27. color: #666;
  28. }
  29. .content .comment_list dl.comment_content {
  30. border-bottom: 1px solid #ccc;
  31. }
  32. .content .comment_add {
  33. text-align: right;
  34. }
  35. .content .comment_add textarea {
  36. width: 98%;
  37. border: 1px solid #ccc;
  38. border-radius: 4px;
  39. background: #fff;
  40. padding: 5px;
  41. font-size: 12px;
  42. color: #666;
  43. resize: none;
  44. }
  45. .content .comment_add input {
  46. cursor:pointer;
  47. }

此刻,添加完CSS样式之后,HTML代码我们实际写为:

  1. <div id="main">
  2. <div class="main_left">
  3. <div id="tabs">
  4. <ul>
  5. <li><a href="tab1.html">tab1</a></li>
  6. <li><a href="tab2.html">tab2</a></li>
  7. <li><a href="tab3.html">tab3</a></li>
  8. </ul>
  9. </div>
  10. <div class="content">
  11. </div>
  12. </div>
  13. <div class="main_right">
  14. <div id="accordion">
  15. <h3>菜单1</h3>
  16. <div><p>内容1</p><p>内容1</p></div>
  17. <h3>菜单2</h3>
  18. <div>内容2</div>
  19. <h3>菜单3</h3>
  20. <div>内容3</div>
  21. </div>
  22. </div>
  23. </div>

接下来,实现点击评论字样展开评论表单的功能:
jQuery代码如下:

  1. $.ajax({
  2. url : "show_content.php",
  3. type : "post",
  4. success : function(response, status, xhr) {
  5. var json = $.parseJSON(response);
  6. var html = "";
  7. var arr = [];
  8. var summary = [];
  9. $.each(json, function(index, value) {
  10. 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>";
  11. });
  12. $(".content").append(html);
  13. $.each($(".editor"), function(index, value) {
  14. arr[index] = $(value).html();
  15. summary[index] = arr[index].substr(0, 200);
  16. if (summary[index].substring(199, 200) == "<") {
  17. summary[index] = replacePos(summary[index], 200, "");
  18. }
  19. if (summary[index].substring(198, 200) == "</") {
  20. summary[index] = replacePos(summary[index], 200, "");
  21. summary[index] = replacePos(summary[index], 199, "");
  22. }
  23. if(arr[index].length > 200) {
  24. summary[index] += '...<span class="down">显示全部</span>'; //一个大的问题,显示全部为动态添加进去,隐藏掉再添加进去的时候,click事件会失效
  25. $(value).html(summary[index]);
  26. }
  27. $(".bottom .up").hide();
  28. });
  29. //动态绑定,用委托绑定处理
  30. $.each($(".editor"), function(index, value) {
  31. $(this).on("click", ".down", function() {
  32. $(".editor").eq(index).html(arr[index]);
  33. $(this).hide();
  34. $(".bottom .up").eq(index).show();
  35. });
  36. });
  37. //统一处理
  38. $.each($(".bottom"), function(index, value) {
  39. $(this).on("click", ".up", function() {
  40. $(".editor").eq(index).html(summary[index]);
  41. $(this).hide();
  42. $(".editor .down").eq(index).show();
  43. });
  44. });
  45. $.each($(".bottom"), function(index, value) {
  46. $(this).on("click", ".comment", function() {
  47. if($.cookie("user")) {
  48. // 点击评论字样只允许评论表单出现一次
  49. if(!$(".comment_list").eq(index).has("form").length) {
  50. $(".comment_list").eq(index).append("<form><dl class='comment_add'><dt><textarea name='comment'></textarea></dt><dd><input type='button' value='发表' /></dd></dl></form>");
  51. }
  52. if($(".comment_list").eq(index).is(":hidden")) {
  53. $(".comment_list").eq(index).show();
  54. } else {
  55. $(".comment_list").eq(index).hide();
  56. }
  57. } else {
  58. $("#error").dialog("open");
  59. setTimeout(function() {
  60. $("#error").dialog("close");
  61. $("#login").dialog("open");
  62. }, 1000);
  63. }
  64. });
  65. });
  66. }
  67. });

二、提交评论

创建数据表:comment,字段分别为:idtitleidusercommentdate等字段。
comment表的结构如图:
知问前端--评论表
add_comment.php

  1. <?php
  2. sleep(1);
  3. require 'config.php';
  4. $query = "INSERT INTO comment (titleid, comment, user, date) VALUES ('{$_POST['titleid']}', '{$_POST['comment']}', '{$_POST['user']}', NOW())";
  5. mysql_query($query) or die('新增失败!'.mysql_error());
  6. echo mysql_affected_rows();
  7. mysql_close();
  8. ?>

由于要上传titleid,所以还需从数据表content表中查出id,即show_content.php修改为:

  1. <?php
  2. require 'config.php';
  3. $query = mysql_query("SELECT id,title,content,user,date FROM question ORDER BY date DESC LIMIT 0,5") or die('SQL 错误!');
  4. $json = '';
  5. while (!!$row = mysql_fetch_array($query, MYSQL_ASSOC)) {
  6. //json格式转码
  7. foreach ( $row as $key => $value ) {
  8. $row[$key] = urlencode(str_replace("\n","", $value));
  9. $row[$key] = urlencode(str_replace("\t","", $value));
  10. }
  11. $json .= urldecode(json_encode($row)).',';
  12. //$json .= json_encode($row).','; //得到json格式
  13. //print_r($row); //以php数组的形式显示出来,javascript不能直接用,那么最好将其保存为json格式
  14. }
  15. //echo $json;
  16. echo '['.substr($json, 0, strlen($json) - 1).']'; //一个json数组,一个数组有3个对象,每个对象就是一个json
  17. mysql_close();
  18. ?>

此时,0条评论字样增加一个自定义属性data-id第一次碰到,要注意,所以此时变为:

  1. <span class='comment' data-id='" + value.id + "'>0条评论</span>

Ajax提交评论的jQuery代码:

  1. $.ajax({
  2. url : "show_content.php",
  3. type : "post",
  4. success : function(response, status, xhr) {
  5. var json = $.parseJSON(response);
  6. var html = "";
  7. var arr = [];
  8. var summary = [];
  9. $.each(json, function(index, value) {
  10. 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>";
  11. });
  12. $(".content").append(html);
  13. $.each($(".editor"), function(index, value) {
  14. arr[index] = $(value).html();
  15. summary[index] = arr[index].substr(0, 200);
  16. if (summary[index].substring(199, 200) == "<") {
  17. summary[index] = replacePos(summary[index], 200, "");
  18. }
  19. if (summary[index].substring(198, 200) == "</") {
  20. summary[index] = replacePos(summary[index], 200, "");
  21. summary[index] = replacePos(summary[index], 199, "");
  22. }
  23. if(arr[index].length > 200) {
  24. summary[index] += '...<span class="down">显示全部</span>'; //一个大的问题,显示全部为动态添加进去,隐藏掉再添加进去的时候,click事件会失效
  25. $(value).html(summary[index]);
  26. }
  27. $(".bottom .up").hide();
  28. });
  29. //动态绑定,用委托绑定处理
  30. $.each($(".editor"), function(index, value) {
  31. $(this).on("click", ".down", function() {
  32. $(".editor").eq(index).html(arr[index]);
  33. $(this).hide();
  34. $(".bottom .up").eq(index).show();
  35. });
  36. });
  37. //统一处理
  38. $.each($(".bottom"), function(index, value) {
  39. $(this).on("click", ".up", function() {
  40. $(".editor").eq(index).html(summary[index]);
  41. $(this).hide();
  42. $(".editor .down").eq(index).show();
  43. });
  44. });
  45. $.each($(".bottom"), function(index, value) {
  46. $(this).on("click", ".comment", function() {
  47. if($.cookie("user")) {
  48. // 点击评论字样只允许评论表单出现一次
  49. if(!$(".comment_list").eq(index).has("form").length) {
  50. $(".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>");
  51. }
  52. if($(".comment_list").eq(index).is(":hidden")) {
  53. $(".comment_list").eq(index).show();
  54. } else {
  55. $(".comment_list").eq(index).hide();
  56. }
  57. $(".comment_list").eq(index).find("input[type=button]").button().click(function() {
  58. //alert("123");
  59. //alert($(".comment_list").eq(index).find("form").find("textarea").val());
  60. var _this = this; // this指代按钮对象
  61. $(".comment_list").eq(index).find("form").ajaxSubmit({
  62. url : "add_comment.php",
  63. type : "post",
  64. beforeSubmit:function(formData,jqForm,options) {
  65. $("#loading").dialog("open");
  66. $(_this).button("disable"); //禁用发布按钮
  67. },
  68. success:function(responseText,statusText) {
  69. //alert(responseText); //新增成功,返回1
  70. if(responseText) {
  71. $(_this).button("enable");
  72. $("#loading").css("background","url(img/success.gif) no-repeat 20px center").html("数据新增成功...");
  73. setTimeout(function() {
  74. $("#loading").dialog("close");
  75. $(".comment_list").eq(index).find("form").resetForm(); //重置表单
  76. $("#loading").css("background","url(img/loading.gif) no-repeat 20px center").html("数据交互中...");
  77. }, 1000);
  78. }
  79. }
  80. });
  81. });
  82. } else {
  83. $("#error").dialog("open");
  84. setTimeout(function() {
  85. $("#error").dialog("close");
  86. $("#login").dialog("open");
  87. }, 1000);
  88. }
  89. });
  90. //$(".comment_add").eq(index).find("input").button();
  91. //$(".comment_list").eq(index).find("input[type=button]").button(); //按钮样式不会发生改变,所以应紧紧接着表单生成,并显示之后
  92. });
  93. }
  94. });
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注