分析ecshop产品评论的原理

2009-08-07 10:38 来源:www.chinab4c.com 作者:ecshop专家

     在最近的日子里面,有个朋友要求我帮他修改ecshop,而且是在产品的详细页面,增加一个评论系统,也就是说产品页面需要两个评论系统。这样的话.不是特别的容易,ecshop的评论都是通过ajax提交,而且通过ajax来返回调用的。

    1:首先,在goods.dwt中增加一个评论的小模块

     <!-- #BeginLibraryItem "/library/comments1.lbi" -->

{insert_scripts files='transport.js,utils.js'}
<div id="ECS_COMMENT1"> {* ECSHOP 提醒您:动态载入comments_list1.lbi,显示评论列表和评论表单 *}{insert name='comments1' type=$type id=$id}</div>

 <!-- #EndLibraryItem -->

   2:在library中增加comment1.lbi

   <meta http-equiv="Content-Type" content="text/html; charset=gbk">
{insert_scripts files='transport.js,utils.js'}
<div id="ECS_COMMENT1"> {* ECSHOP 提醒您:动态载入comments_list.lbi,显示评论列表和评论表单 *}{insert name='comments1' type=$type id=$id}</div>
   增加一个id="ECS_COMMENT1"的层.

   3:在library中增加一个comments_list.lbi

    <meta http-equiv="Content-Type" content="text/html; charset=gbk">
<!--用户评论 START-->
     <div class="box">
     <div class="box_1">
      <h3><span class="text">购买咨询评论</span>好评:{$type1}&nbsp;中评:{$type2}&nbsp;差评:{$type3}&nbsp;({$lang.total}<font class="f1">{$pager1.record_count}</font>{$lang.user_comment_num})</h3>
      <div class="boxCenterList clearfix" style="height:1%;">
       <ul class="comments">
       <!-- {if $comments1} -->
       <!-- {foreach from=$comments1 item=comment} -->
        <li class="word">
        <font class="f2"><!-- {if $comment.username} -->{$comment.username|escape:html}<!-- {else} -->{$lang.anonymous}<!-- {/if} --></font> <font class="f3">( {$comment.add_time} )</font><br />
        <img src="../images/stars{$comment.rank}.gif" alt="{$comment.comment_rank}" />
        <p>{$comment.content}</p>
    <!-- {if $comment.re_content} -->
        <p><font class="f1">{$lang.admin_username}</font>{$comment.re_content}</p>
    <!-- {/if} -->
        </li>
        <!-- {/foreach} -->
        <!--{else}-->
        <li>{$lang.no_comments}</li>
        <!--{/if}-->
       </ul>
       <!--翻页 start-->
       <div id="pagebar" class="f_r">
        <form name="selectPageForm" action="{$smarty.server.PHP_SELF}" method="get">
        <!-- {if $pager1.styleid eq 0 } -->
        <div id="pager">
          {$lang.pager_1}{$pager1.record_count}{$lang.pager_2}{$lang.pager_3}{$pager1.page_count}{$lang.pager_4} <span> <a href="{$pager1.page_first}">{$lang.page_first}</a> <a href="{$pager1.page_prev}">{$lang.page_prev}</a> <a href="{$pager1.page_next}">{$lang.page_next}</a> <a href="{$pager1.page_last}">{$lang.page_last}</a> </span>
            <!--{foreach from=$pager1.search key=key item=item}-->
            <input type="hidden" name="{$key}" value="{$item}" />
            <!--{/foreach}-->
        </div>
        <!--{else}-->

        <!--翻页 start-->
         <div id="pager" class="pagebar">
          <span class="f_l f6" style="margin-right:10px;">{$lang.total} <b>{$pager1.record_count}</b> {$lang.user_comment_num}</span>
          <!-- {if $pager1.page_first} --><a href="{$pager1.page_first}">1 ...</a><!-- {/if} -->
          <!-- {if $pager1.page_prev} --><a class="prev" href="{$pager1.page_prev}">{$lang.page_prev}</a><!-- {/if} -->
          <!--{foreach from=$pager1.page_number key=key item=item}-->
                <!-- {if $pager1.page eq $key} -->
                <span class="page_now">{$key}</span>
                <!-- {else} -->
                <a href="{$item}">[{$key}]</a>
                <!-- {/if} -->
            <!--{/foreach}-->

          <!-- {if $pager1.page_next} --><a class="next" href="{$pager1.page_next}">{$lang.page_next}</a><!-- {/if} -->
          <!-- {if $pager1.page_last} --><a class="last" href="{$pager1.page_last}">...{$pager1.page_count}</a><!-- {/if} -->
          <!-- {if $pager1.page_kbd} -->
            <!--{foreach from=$pager1.search key=key item=item}-->
            <input type="hidden" name="{$key}" value="{$item}" />
            <!--{/foreach}-->
            <kbd style="float:left; margin-left:8px; position:relative; bottom:3px;"><input type="text" name="page" onkeydown="if(event.keyCode==13)selectPage(this)" size="3" class="B_blue" /></kbd>
            <!-- {/if} -->
        </div>
        <!--翻页 END-->

        <!-- {/if} -->
        </form>
        <script type="Text/Javascript" language="JavaScript">
        <!--
        {literal}
        function selectPage(sel)
        {
          sel.form.submit();
        }
        {/literal}
        //-->
        </script>
      </div>
      <!--翻页 END-->
      <div class="blank5"></div>
      <!--评论表单 start-->
      <div class="commentsList">
      <form action="javascript:;" onsubmit="submitComment1(this)" method="post" name="commentForm1" id="commentForm1">
       <table width="710" border="0" cellspacing="5" cellpadding="0">
        <tr>
          <td width="64" align="right">{$lang.username}:</td>
          <td width="631"{if !$enabled_captcha}{/if}><!--{if $smarty.session.user_name}-->{$smarty.session.user_name}<!--{else}-->{$lang.anonymous}<!--{/if}--></td>
        </tr>
        <tr>
          <td align="right">E-mail:</td>
          <td>
          <input type="text" name="email" id="email"  maxlength="100" value="{$smarty.session.email|escape}" class="inputBorder"/>          </td>
        </tr>
        <tr>
          <td align="right">购买评价:</td>
          <td><label>
            <input type="radio" name="type_count" value="1">
           好评 
           <input type="radio" name="type_count" value="2">
           中评
            <input type="radio" name="type_count" value="3">
            差评
          </label></td>
        </tr>
        <tr>
          <td align="right">{$lang.comment_rank}:</td>
          <td>
          <input name="comment_rank" type="radio" value="1" id="comment_rank1" /> <img src="../images/stars1.gif" />
          <input name="comment_rank" type="radio" value="2" id="comment_rank2" /> <img src="../images/stars2.gif" />
          <input name="comment_rank" type="radio" value="3" id="comment_rank3" /> <img src="../images/stars3.gif" />
          <input name="comment_rank" type="radio" value="4" id="comment_rank4" /> <img src="../images/stars4.gif" />
          <input name="comment_rank" type="radio" value="5" checked="checked" id="comment_rank5" /> <img src="../images/stars5.gif" />          </td>
        </tr>
        <tr>
          <td align="right" valign="top">{$lang.comment_content}:</td>
          <td>
          <textarea name="content" class="inputBorder" style="height:50px; width:620px;"></textarea>
          <input type="hidden" name="cmt_type" value="2" />
          <input type="hidden" name="id" value="{$id}" />          </td>
        </tr>
        <tr>
          <td colspan="2">
          <!-- 判断是否启用验证码{if $enabled_captcha} -->
          <div style="padding-left:15px; text-align:left; float:left;">
          {$lang.comment_captcha}:<input type="text" name="captcha"  class="inputBorder" style="width:50px; margin-left:5px;"/>
          <img src="captcha.php?{$rand}" alt="captcha" onClick="this.src='captcha.php?'+Math.random()" class="captcha">          </div>
          <!-- {/if} -->
          <input name="" type="submit"  value="" class="f_r" style="border:none; background:url(../images/commentsBnt.gif); width:75px; height:21px; margin-right:8px;">          </td>
        </tr>
      </table>
      </form>
      </div>
      <!--评论表单 end-->
      </div>
     </div>
    </div>
    <div class="blank5"></div>
  <!--用户评论 END-->
<script type="text/javascript">
//<![CDATA[
{foreach from=$lang.cmt_lang item=item key=key}
var {$key} = "{$item}";
{/foreach}
{literal}
/**
 * 提交评论信息
*/
function submitComment1(frm)
{
  var cmt = new Object;

  //cmt.username        = frm.elements['username'].value;
  cmt.email           = frm.elements['email'].value;
  cmt.content         = frm.elements['content'].value;
 
 
  cmt.type            = frm.elements['cmt_type'].value;
  cmt.id              = frm.elements['id'].value;
  cmt.enabled_captcha = frm.elements['enabled_captcha'] ? frm.elements['enabled_captcha'].value : '0';
  cmt.captcha         = frm.elements['captcha'] ? frm.elements['captcha'].value : '';
  cmt.rank            = 0;
 for (i = 0; i < frm.elements['type_count'].length; i++)
  {
    if (frm.elements['type_count'][i].checked)
    {
       cmt.type_count = frm.elements['type_count'][i].value;
     }
  }
  for (i = 0; i < frm.elements['comment_rank'].length; i++)
  {
    if (frm.elements['comment_rank'][i].checked)
    {
       cmt.rank = frm.elements['comment_rank'][i].value;
     }
  }

//  if (cmt.username.length == 0)
//  {
//     alert(cmt_empty_username);
//     return false;
//  }

  if (cmt.email.length > 0)
  {
     if (!(Utils.isEmail(cmt.email)))
     {
        alert(cmt_error_email);
        return false;
      }
   }
   else
   {
        alert(cmt_empty_email);
        return false;
   }

   if (cmt.content.length == 0)
   {
      alert(cmt_empty_content);
      return false;
   }

   if (cmt.enabled_captcha > 0 && cmt.captcha.length == 0 )
   {
      alert(captcha_not_null);
      return false;
   }

   Ajax.call('comment1.php', 'cmt=' + cmt.toJSONString(), commentResponse1, 'POST', 'JSON');
   return false;
}

/**
 * 处理提交评论的反馈信息
*/
  function commentResponse1(result)
  {
    if (result.message)
    {
      alert(result.message);
    }

    if (result.error == 0)
    {
      var layer = document.getElementById('ECS_COMMENT1');

      if (layer)
      {
        layer.innerHTML = result.content;
      }
    }
  }
{/literal}
//]]>
</script>

  4:在lib_insert.php中增加函数

   function insert_comments1($arr)
{
    $need_cache = $GLOBALS['smarty']->caching;
    $need_compile = $GLOBALS['smarty']->force_compile;

    $GLOBALS['smarty']->caching = false;
    $GLOBALS['smarty']->force_compile = true;

    /* 验证码相关设置 */
    if ((intval($GLOBALS['_CFG']['captcha']) & CAPTCHA_COMMENT) && gd_version() > 0)
    {
        $GLOBALS['smarty']->assign('enabled_captcha', 1);
        $GLOBALS['smarty']->assign('rand', mt_rand());
    }
    $GLOBALS['smarty']->assign('username',     stripslashes($_SESSION['user_name']));
    $GLOBALS['smarty']->assign('email',        $_SESSION['email']);
    $GLOBALS['smarty']->assign('comment_type', $arr['type']);
    $GLOBALS['smarty']->assign('id',           $arr['id']);
    $cmt = assign_comment1($arr['id'],          $arr['type']);
    $GLOBALS['smarty']->assign('comments1',     $cmt['comments']);
    $GLOBALS['smarty']->assign('pager1',        $cmt['pager']);
 $GLOBALS['smarty'] -> assign('type1',$GLOBALS['db']-> getOne("select count(*) from ".$GLOBALS['ecs']->table('comment')." where id_value = ".$arr['id']." and type_count = 1"));
    $GLOBALS['smarty'] -> assign('type2',$GLOBALS['db']-> getOne("select count(*) from ".$GLOBALS['ecs']->table('comment')." where id_value = ".$arr['id']." and type_count = 2"));
    $GLOBALS['smarty'] -> assign('type3',$GLOBALS['db']-> getOne("select count(*) from ".$GLOBALS['ecs']->table('comment')." where id_value = ".$arr['id']." and type_count = 3"));
   
    $val = $GLOBALS['smarty']->fetch('library/comments_list1.lbi');

    $GLOBALS['smarty']->caching = $need_cache;
    $GLOBALS['smarty']->force_compile = $need_compile;

    return $val;
}
   用来显示comments_list1.lbi

   5:在lib_main.php中增加函数

    function assign_comment1($id, $type, $page = 1)
{
    /* 取得评论列表 */
    $count = $GLOBALS['db']->getOne('SELECT COUNT(*) FROM ' .$GLOBALS['ecs']->table('comment').
           " WHERE id_value = '$id' AND comment_type = '2' AND status = 1 AND parent_id = 0");
    $size  = !empty($GLOBALS['_CFG']['comments_number']) ? $GLOBALS['_CFG']['comments_number'] : 5;

    $page_count = ($count > 0) ? intval(ceil($count / $size)) : 1;

    $sql = 'SELECT * FROM ' . $GLOBALS['ecs']->table('comment') .
            " WHERE id_value = '$id' AND comment_type = '2' AND status = 1 AND parent_id = 0".
            ' ORDER BY comment_id DESC';
    $res = $GLOBALS['db']->selectLimit($sql, $size, ($page-1) * $size);

    $arr = array();
    $ids = '';
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $ids .= $ids ? ",$row[comment_id]" : $row['comment_id'];
        $arr[$row['comment_id']]['id']       = $row['comment_id'];
        $arr[$row['comment_id']]['email']    = $row['email'];
        $arr[$row['comment_id']]['username'] = $row['user_name'];
        $arr[$row['comment_id']]['content']  = str_replace('\r\n', '<br />', htmlspecialchars($row['content']));
        $arr[$row['comment_id']]['content']  = str_replace('\n', '<br />', $arr[$row['comment_id']]['content']);
        $arr[$row['comment_id']]['rank']     = $row['comment_rank'];
        $arr[$row['comment_id']]['add_time'] = local_date($GLOBALS['_CFG']['time_format'], $row['add_time']);
    }
    /* 取得已有回复的评论 */
    if ($ids)
    {
        $sql = 'SELECT * FROM ' . $GLOBALS['ecs']->table('comment') .
                " WHERE parent_id IN( $ids )";
        $res = $GLOBALS['db']->query($sql);
        while ($row = $GLOBALS['db']->fetch_array($res))
        {
            $arr[$row['parent_id']]['re_content']  = str_replace('\n', '<br />', htmlspecialchars($row['content']));
            $arr[$row['parent_id']]['re_add_time'] = local_date($GLOBALS['_CFG']['time_format'], $row['add_time']);
            $arr[$row['parent_id']]['re_email']    = $row['email'];
            $arr[$row['parent_id']]['re_username'] = $row['user_name'];
        }
    }
    /* 分页样式 */
    //$pager['styleid'] = isset($GLOBALS['_CFG']['page_style'])? intval($GLOBALS['_CFG']['page_style']) : 0;
    $pager['page']         = $page;
    $pager['size']         = $size;
    $pager['record_count'] = $count;
    $pager['page_count']   = $page_count;
    $pager['page_first']   = "javascript:gotoPage1(1,$id,2)";
    $pager['page_prev']    = $page > 1 ? "javascript:gotoPage1(" .($page-1). ",$id,2)" : 'javascript:;';
    $pager['page_next']    = $page < $page_count ? 'javascript:gotoPage1(' .($page + 1) . ",$id,2)" : 'javascript:;';
    $pager['page_last']    = $page < $page_count ? 'javascript:gotoPage1(' .$page_count. ",$id,2)"  : 'javascript:;';

    $cmt = array('comments' => $arr, 'pager' => $pager);

    return $cmt;
}

   用来给comment_list.lbi赋于流言的内容.

  6:在js/common.js中增加分页脚本函数gotoPage1,用来返回ajax的值.

   function gotoPage1(page, id, type)
{
  Ajax.call('comment1.php?act=gotopage', 'page=' + page + '&id=' + id + '&type=' + type, gotoPageResponse1, 'GET', 'JSON');
}

function gotoPageResponse1(result)
{
  document.getElementById("ECS_COMMENT1").innerHTML = result.content;
}

  7:做一个comment1.php,让他来处理第二套评论系统的数据

   if ($result['error'] == 0)
{
    $comments = assign_comment1($cmt->id, $cmt->type, $cmt->page);

    $smarty->assign('comment_type', $cmt->type);
    $smarty->assign('id',           $cmt->id);
    $smarty->assign('username',     $_SESSION['user_name']);
    $smarty->assign('email',        $_SESSION['email']);
    $smarty->assign('comments1',     $comments['comments']);
    $smarty->assign('pager1',        $comments['pager']);
 $smarty -> assign('type1',$GLOBALS['db']-> getOne("select count(*) from ".$GLOBALS['ecs']->table('comment')." where id_value = ".$cmt -> id." and type_count = 1"));
    $smarty -> assign('type2',$GLOBALS['db']-> getOne("select count(*) from ".$GLOBALS['ecs']->table('comment')." where id_value = ".$cmt -> id." and type_count = 2"));
    $smarty -> assign('type3',$GLOBALS['db']-> getOne("select count(*) from ".$GLOBALS['ecs']->table('comment')." where id_value = ".$cmt -> id." and type_count = 3"));
   
    /* 验证码相关设置 */
    if ((intval($_CFG['captcha']) & CAPTCHA_COMMENT) && gd_version() > 0)
    {
        $smarty->assign('enabled_captcha', 1);
        $smarty->assign('rand', mt_rand());
    }

    $result['message'] = $_CFG['comment_check'] ? $_LANG['cmt_submit_wait'] : $_LANG['cmt_submit_done'];
    $result['content'] = $smarty->fetch("library/comments_list1.lbi");
}
 

  这样就完毕了。.

  来源:中国B4C电子商务