[关闭]
@liayun 2016-05-14T14:36:24.000000Z 字数 14602 阅读 1582

知问前端--Ajax显示评论

知问前端


本文开始主要实现Ajax显示评论功能。

一、显示评论

question表中查出问题描述时,还要显示此问题共有多少条评论,所以得修改show_content.php为:

  1. <?php
  2. require 'config.php';
  3. $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 错误!');
  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. ?>

要点:

  1. ajax远程加载comment表数据时,只加载一次。即$.ajax();只能在以下代码块中使用:

    1. if(!$(".comment_list").eq(index).has("form").length) {
    2. $.ajax(...);
    3. }

    而不能在以下代码块中使用:

    1. if($(".comment_list").eq(index).is(":hidden")) {
    2. $(".comment_list").eq(index).show();
    3. //$.ajax(); //远程加载不应放在这儿
    4. }
  2. 顺序问题:
    ①评论列表显示在前,评论表单在后,所以得在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 + "'>" + value.count + "条评论</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. var comment_this = this;
  48. if($.cookie("user")) {
  49. // 点击评论字样只允许评论表单出现一次
  50. if(!$(".comment_list").eq(index).has("form").length) {
  51. $.ajax({
  52. url : "show_comment.php",
  53. type : "post",
  54. beforeSend : function(jqXHR, settings) {
  55. $(".comment_list").eq(index).append("<dl class='comment_load'><dd>正在加载评论</dd></dl>");
  56. },
  57. success : function(response, status) {
  58. $(".comment_list").eq(index).find(".comment_load").hide();
  59. var json_comment = $.parseJSON(response);
  60. $.each(json_comment, function(index2, value) {
  61. $(".comment_list").eq(index).append("<dl class='comment_content'><dt>" + value.user + "</dt><dd>" + value.comment + "</dd><dd class='date'>" + value.date + "</dd></dl>");
  62. });
  63. $(".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>");
  64. }
  65. });
  66. }
  67. if($(".comment_list").eq(index).is(":hidden")) {
  68. $(".comment_list").eq(index).show();
  69. } else {
  70. $(".comment_list").eq(index).hide();
  71. }
  72. //ajax远程加载,可能延迟1s、2s、3s
  73. //此时的表单在加载之前就已经执行了,会导致无法提交表单,而且按钮变成初始状态
  74. $(".comment_list").eq(index).find("input[type=button]").button().click(function() {
  75. //alert("123");
  76. //alert($(".comment_list").eq(index).find("form").find("textarea").val());
  77. var _this = this; // this指代按钮对象
  78. $(".comment_list").eq(index).find("form").ajaxSubmit({
  79. url : "add_comment.php",
  80. type : "post",
  81. beforeSubmit:function(formData,jqForm,options) {
  82. $("#loading").dialog("open");
  83. $(_this).button("disable"); //禁用发布按钮
  84. },
  85. success:function(responseText,statusText) {
  86. //alert(responseText); //新增成功,返回1
  87. if(responseText) {
  88. $(_this).button("enable");
  89. $("#loading").css("background","url(img/success.gif) no-repeat 20px center").html("数据新增成功...");
  90. setTimeout(function() {
  91. $("#loading").dialog("close");
  92. $(".comment_list").eq(index).find("form").resetForm(); //重置表单
  93. $("#loading").css("background","url(img/loading.gif) no-repeat 20px center").html("数据交互中...");
  94. }, 1000);
  95. }
  96. }
  97. });
  98. });
  99. } else {
  100. $("#error").dialog("open");
  101. setTimeout(function() {
  102. $("#error").dialog("close");
  103. $("#login").dialog("open");
  104. }, 1000);
  105. }
  106. });
  107. });
  108. }
  109. });

正确的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 + "'>" + value.count + "条评论</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. var comment_this = this;
  48. if($.cookie("user")) {
  49. // 点击评论字样只允许评论表单出现一次
  50. if(!$(".comment_list").eq(index).has("form").length) {
  51. $.ajax({
  52. url : "show_comment.php",
  53. type : "post",
  54. beforeSend : function(jqXHR, settings) {
  55. $(".comment_list").eq(index).append("<dl class='comment_load'><dd>正在加载评论</dd></dl>");
  56. },
  57. success : function(response, status) {
  58. $(".comment_list").eq(index).find(".comment_load").hide();
  59. var json_comment = $.parseJSON(response);
  60. $.each(json_comment, function(index2, value) {
  61. $(".comment_list").eq(index).append("<dl class='comment_content'><dt>" + value.user + "</dt><dd>" + value.comment + "</dd><dd class='date'>" + value.date + "</dd></dl>");
  62. });
  63. $(".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>");
  64. $(".comment_list").eq(index).find("input[type=button]").button().click(function() {
  65. //alert("123");
  66. //alert($(".comment_list").eq(index).find("form").find("textarea").val());
  67. var _this = this; // this指代按钮对象
  68. $(".comment_list").eq(index).find("form").ajaxSubmit({
  69. url : "add_comment.php",
  70. type : "post",
  71. beforeSubmit:function(formData,jqForm,options) {
  72. $("#loading").dialog("open");
  73. $(_this).button("disable"); //禁用发布按钮
  74. },
  75. success:function(responseText,statusText) {
  76. //alert(responseText); //新增成功,返回1
  77. if(responseText) {
  78. $(_this).button("enable");
  79. $("#loading").css("background","url(img/success.gif) no-repeat 20px center").html("数据新增成功...");
  80. setTimeout(function() {
  81. $("#loading").dialog("close");
  82. $(".comment_list").eq(index).find("form").resetForm(); //重置表单
  83. $("#loading").css("background","url(img/loading.gif) no-repeat 20px center").html("数据交互中...");
  84. }, 1000);
  85. }
  86. }
  87. });
  88. });
  89. }
  90. });
  91. }
  92. if($(".comment_list").eq(index).is(":hidden")) {
  93. $(".comment_list").eq(index).show();
  94. } else {
  95. $(".comment_list").eq(index).hide();
  96. }
  97. } else {
  98. $("#error").dialog("open");
  99. setTimeout(function() {
  100. $("#error").dialog("close");
  101. $("#login").dialog("open");
  102. }, 1000);
  103. }
  104. });
  105. });
  106. }
  107. });

可以对class='comment_load'修饰:

  1. .content .comment_load dd {
  2. background: url(img/comment_load.gif) no-repeat 75px 45%;
  3. }

提交评论时,自动显示为在第一条的位置,实现方法即为在表单重置之前,将新的评论数据置为第一条目录,修改评论提交代码如下:

  1. $(".comment_list").eq(index).find("input[type=button]").button().click(function() {
  2. //alert("123");
  3. //alert($(".comment_list").eq(index).find("form").find("textarea").val());
  4. var _this = this;
  5. $(".comment_list").eq(index).find("form").ajaxSubmit({
  6. url : "add_comment.php",
  7. type : "post",
  8. beforeSubmit:function(formData,jqForm,options) {
  9. $("#loading").dialog("open");
  10. $(_this).button("disable"); //禁用发布按钮
  11. },
  12. success:function(responseText,statusText) {
  13. //alert(responseText); //新增成功,返回1
  14. if(responseText) {
  15. $(_this).button("enable");
  16. $("#loading").css("background","url(img/success.gif) no-repeat 20px center").html("数据新增成功...");
  17. setTimeout(function() {
  18. var date = new Date();
  19. $("#loading").dialog("close");
  20. $(".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>');
  21. $(".comment_list").eq(index).find("form").resetForm(); //重置表单
  22. $("#loading").css("background","url(img/loading.gif) no-repeat 20px center").html("数据交互中...");
  23. }, 1000);
  24. }
  25. }
  26. });
  27. });

二、分页显示评论

以上代码还有问题:
问题一,无论点击哪个问题下的评论,均全部显示评论表comment中全部评论,而非显示对应问题下的评论。
问题二,即分页显示评论。
两者解决办法:
show_comment.php代码:

  1. <?php
  2. sleep(1);
  3. require 'config.php';
  4. $_sql = mysql_query("SELECT COUNT(*) AS count FROM comment WHERE titleid = '{$_POST['titleid']}'");
  5. $_result = mysql_fetch_array($_sql, MYSQL_ASSOC);
  6. //echo $_result['count'];
  7. $_pagesize = 2;
  8. $_count = ceil($_result['count'] / $_pagesize);
  9. //echo $_count;
  10. $_page = 1;
  11. if(!isset($_POST['page'])) {
  12. $_page = 1;
  13. } else {
  14. $_page = $_POST['page'];
  15. if($_page > $_count) {
  16. $_page = $_count;
  17. }
  18. }
  19. $_limit = ($_page - 1) * $_pagesize;
  20. $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 错误!');
  21. $json = '';
  22. while (!!$row = mysql_fetch_array($query, MYSQL_ASSOC)) {
  23. //json格式转码
  24. foreach ( $row as $key => $value ) {
  25. $row[$key] = urlencode(str_replace("\n","", $value));
  26. $row[$key] = urlencode(str_replace("\t","", $value));
  27. }
  28. $json .= urldecode(json_encode($row)).',';
  29. //$json .= json_encode($row).','; //得到json格式
  30. //print_r($row); //以php数组的形式显示出来,javascript不能直接用,那么最好将其保存为json格式
  31. }
  32. //echo $json;
  33. echo '['.substr($json, 0, strlen($json) - 1).']'; //一个json数组,一个数组有3个对象,每个对象就是一个json
  34. mysql_close();
  35. ?>

jQuery代码如下:

  1. $.each($(".bottom"), function(index, value) {
  2. $(this).on("click", ".comment", function() {
  3. var comment_this = this;
  4. //alert("123");
  5. if($.cookie("user")) {
  6. if(!$(".comment_list").eq(index).has("form").length) {
  7. $.ajax({
  8. url : "show_comment.php",
  9. type : "post",
  10. data : {
  11. titleid : $(comment_this).attr("data-id")
  12. },
  13. beforeSend : function(jqXHR, settings) {
  14. $(".comment_list").eq(index).append("<dl class='comment_load'><dd>正在加载评论</dd></dl>");
  15. },
  16. success : function(response, status) {
  17. $(".comment_list").eq(index).find(".comment_load").hide();
  18. // 初始加载第1页(每页2条评论)
  19. var json_comment = $.parseJSON(response);
  20. var count = 0;
  21. $.each(json_comment, function(index2, value) {
  22. //alert(value.count); //查询总页数
  23. count = value.count;
  24. $(".comment_list").eq(index).append("<dl class='comment_content'><dt>" + value.user + "</dt><dd>" + value.comment + "</dd><dd class='date'>" + value.date + "</dd></dl>");
  25. });
  26. $(".comment_list").eq(index).append("<dl><dd><span class='load_more'>加载更多评论</span></dd></dl>");
  27. // 有了"加载更多评论"按钮,则从第2页开始加载评论
  28. var page = 2;
  29. // 如果评论总数<=2,"加载更多评论"按钮的click事件销毁,并隐藏
  30. if (page > count) {
  31. //将click事件销毁掉,所以用on()事件
  32. $(".comment_list").eq(index).find(".load_more").off("click");
  33. $(".comment_list").eq(index).find(".load_more").hide();
  34. }
  35. $(".comment_list").eq(index).find(".load_more").button().on("click", function() {
  36. $(".comment_list").eq(index).find(".load_more").button("disable");
  37. $.ajax({
  38. url : "show_comment.php",
  39. type : "post",
  40. data : {
  41. titleid : $(comment_this).attr("data-id"),
  42. page : page //将要显示的第x页的x传递到服务器
  43. },
  44. beforeSend : function(jqXHR, settings) {
  45. $(".comment_list").eq(index).find(".load_more").html("<img src = 'img/more_load.gif' />");
  46. },
  47. success : function(response, status) {
  48. var json_comment_more = $.parseJSON(response);
  49. $.each(json_comment_more, function(index3, value) {
  50. $(".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>");
  51. });
  52. $(".comment_list").eq(index).find(".load_more").button("enable");
  53. $(".comment_list").eq(index).find(".load_more").html("加载更多评论");
  54. page++; //不断显示下一页
  55. // 要查询的页数超过总页数,"加载更多评论"按钮的click事件销毁,并隐藏
  56. if (page > count) {
  57. //将click事件销毁掉,所以用on()事件
  58. $(".comment_list").eq(index).find(".load_more").off("click");
  59. $(".comment_list").eq(index).find(".load_more").hide();
  60. }
  61. }
  62. });
  63. });
  64. $(".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>");
  65. // 所以type="button"的按钮的click事件要放置在表单生成之后
  66. $(".comment_list").eq(index).find("input[type=button]").button().click(function() {
  67. //alert("123");
  68. //alert($(".comment_list").eq(index).find("form").find("textarea").val());
  69. var _this = this;
  70. $(".comment_list").eq(index).find("form").ajaxSubmit({
  71. url : "add_comment.php",
  72. type : "post",
  73. beforeSubmit:function(formData,jqForm,options) {
  74. $("#loading").dialog("open");
  75. $(_this).button("disable"); //禁用发布按钮
  76. },
  77. success:function(responseText,statusText) {
  78. //alert(responseText); //新增成功,返回1
  79. if(responseText) {
  80. $(_this).button("enable");
  81. $("#loading").css("background","url(img/success.gif) no-repeat 20px center").html("数据新增成功...");
  82. setTimeout(function() {
  83. var date = new Date();
  84. $("#loading").dialog("close");
  85. $(".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>');
  86. $(".comment_list").eq(index).find("form").resetForm(); //重置表单
  87. $("#loading").css("background","url(img/loading.gif) no-repeat 20px center").html("数据交互中...");
  88. }, 1000);
  89. }
  90. }
  91. });
  92. });
  93. }
  94. });
  95. }
  96. if($(".comment_list").eq(index).is(":hidden")) {
  97. $(".comment_list").eq(index).show();
  98. //$.ajax(); //远程加载不应放在这儿
  99. } else {
  100. $(".comment_list").eq(index).hide();
  101. }
  102. } else {
  103. $("#error").dialog("open");
  104. setTimeout(function() {
  105. $("#error").dialog("close");
  106. $("#login").dialog("open");
  107. }, 1000);
  108. }
  109. });
  110. });

添加css样式:

  1. .content .load_more {
  2. width: 100%;
  3. margin: 10px 0 0 0;
  4. height: 30px;
  5. line-height: 30px;
  6. }
  7. .content .load_more img {
  8. padding: 5px 0 0 0;
  9. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注