In website operation, user interaction is a key factor in increasing community activity.The like comment feature not only encourages user participation, but also helps website administrators identify popular comment content.For websites using AnQiCMS, implementing this feature and updating the likes in real-time can be done through the built-in template tags and a little frontend JavaScript code.

Basic comment function: How to display the comment list

In AnQi CMS, the core of the comment feature lies incommentListTemplate tag. It allows you to flexibly display related comments for the document on the document detail page.Generally, we would place the comment list below the document content to guide users in participating in discussions.

First, in your document detail template file (such asarchive/detail.html), you need to go througharchive.IdGet the current article ID and pass it as a parameter tocommentListthe tag. A basic comment list display code might look like this:

<div class="comments-section">
    <h3>用户评论</h3>
    {% commentList comments with archiveId=archive.Id type="list" limit="10" %}
        {% for item in comments %}
            <div class="comment-item" id="comment-{{item.Id}}">
                <div class="comment-header">
                    <span class="username">{{item.UserName}}</span>
                    <span class="timestamp">{{stampToDate(item.CreatedTime, "2006-01-02 15:04")}}</span>
                </div>
                <div class="comment-content">
                    {% if item.Status != 1 %}
                        <p class="moderation-notice">该评论正在审核中...</p>
                    {% else %}
                        <p>{{item.Content}}</p>
                    {% endif %}
                </div>
                <div class="comment-actions">
                    <a href="javascript:;" class="like-button" data-comment-id="{{item.Id}}">
                        赞 (<span class="vote-count">{{item.VoteCount}}</span>)
                    </a>
                    {% if item.Parent %}
                        <div class="reply-to">回复 @{{item.Parent.UserName}}</div>
                    {% endif %}
                </div>
            </div>
        {% empty %}
            <p>目前还没有评论,快来发表你的看法吧!</p>
        {% endfor %}
    {% endcommentList %}
</div>

In this template code, we set a unique ID for each comment item (id="comment-{{item.Id}}") and added a like button on itdata-comment-id="{{item.Id}}"The custom attribute is used to store the comment ID. Moreover, we wrap the like count in a<span>tag and assign avote-countThe class name, convenient for updating this value later through JavaScript.{{item.VoteCount}}It is the like count that comes with the Anqi CMS comment list tag.

To implement the comment like function.

The AnQi CMS provides a dedicated API interface for liking comments.When the user clicks the like button, we need to send a request to this interface through the front-end JavaScript to inform the system which comment has been liked.

The like API interface is:/comment/praiseIt receives a parameter via POST request:idThis represents the comment ID. This API will return JSON data that includes the updated number of likes.

The following is a JavaScript code implemented using jQuery, you can place it in the template file.</body>Before the tag, or in a separate JavaScript file:

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
    // 监听所有具有 'like-button' 类名的元素的点击事件
    $('.like-button').on('click', function(e) {
        e.preventDefault(); // 阻止默认的链接跳转行为

        var $this = $(this); // 缓存当前点击的按钮
        var commentId = $this.data('comment-id'); // 获取评论ID

        if (!commentId) {
            console.error('评论ID未找到。');
            return;
        }

        // 发送AJAX POST请求到点赞接口
        $.ajax({
            url: '/comment/praise',
            method: 'POST',
            data: { id: commentId },
            dataType: 'json', // 预期服务器返回JSON数据
            success: function(response) {
                if (response.code === 0) { // 假设 code: 0 表示成功
                    // 更新点赞数
                    $this.find('.vote-count').text(response.data.vote_count);
                    alert(response.msg); // 提示用户点赞成功或取消成功
                } else {
                    alert(response.msg || '点赞操作失败,请重试。'); // 提示错误信息
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error('AJAX请求失败:', textStatus, errorThrown);
                alert('网络错误或服务器异常,请稍后再试。');
            }
        });
    });
});
</script>

This JavaScript code will first run after the page has loaded, for all elements withlike-buttonThe element binds the click event of the class name. When the user clicks these buttons, it will obtain the corresponding comment ID and send a POST request to/comment/praisethe interface.

Like count is updated in real time

The key to updating the like count in real time lies in the successful AJAX requestsuccesscallback function. This part of the logic has already been included in the above JavaScript code:

success: function(response) {
    if (response.code === 0) { // 假设 code: 0 表示成功
        // 更新点赞数
        $this.find('.vote-count').text(response.data.vote_count);
        alert(response.msg); // 提示用户点赞成功或取消成功
    } else {
        alert(response.msg || '点赞操作失败,请重试。'); // 提示错误信息
    }
}

When the AnQi CMS backend successfully handles the like request and returns data (response.code === 0It will beresponse.dataContains the latestvote_count.$this.find('.vote-count').text(response.data.vote_count);The purpose of this line of code is:

  1. $this: Represents the like button clicked by the current user (.like-button)
  2. .find('.vote-count'): Find the class named inside the current buttonvote-countThe element, which is used to display the number of likes<span>.
  3. .text(response.data.vote_count)Set<span>Update the text content within the tag to the latest number of likes returned by the backend.

Thus, users can see the change in likes immediately without refreshing the page, thereby obtaining a smoother interactive experience.

Integrate it into your template.

To fully implement the comment like function, you need:

  1. In the comment list template (such asarchive/detail.html)commentListLabel display comments, and add a like button fordata-comment-idattributes andvote-countdisplay area.}
  2. Introduce the jQuery library (if it has not been introduced on your website).
  3. Add the above JavaScript code to your template file, usually placed in</body>Make sure the DOM element is fully loaded before closing the tag.

By following these steps, you can make your secure CMS website comment section more interactive with a like feature.


Frequently Asked Questions (FAQ)

1. Why does the like count not update in real time, or there is no reaction after clicking?

This is usually due to incorrect execution of front-end JavaScript code or API request failure.You can try to open the browser's developer tools (F12), switch to the 'Console' (console) and 'Network' (network) panels.

  • Console: Check for JavaScript error messages.
  • NetworkAfter clicking the like button, observe if there is a shift/comment/praiseInitiate a POST request and view the response status code (should be 200) and the returned data.If the request is not made, the status code is not 200, or the returned data format is incorrect, then you need to check the JavaScript code or server configuration.Also, make sure you have correctly included the jQuery library.

2. How does Anqi CMS prevent users from maliciously liking or repeatedly liking?

Of Security CMS/comment/praiseThe interface is built-in with anti-repeat like logic. Usually, the system will judge based on the user's IP address and comment ID.If the same IP votes multiple times for the same comment in a short period of time, or votes again after voting, the system will recognize and take corresponding actions (such as blocking further votes and returning a prompt, or performing the operation of canceling the vote).The specific strategy is determined by the Anqi CMS backend, and users do not need to perform any additional processing on the frontend to obtain this security protection.

3. Can I customize the style and prompt information of the like button?

Of course you can. The style of the like button is completely determined by the front-end HTML structure and CSS style. You can modify.like-buttonand.vote-countCSS to beautify them. As for the hints, in JavaScript'ssuccessanderror