How to implement the like function for comments in Anqi CMS and update the display of likes in real time?

Calendar 👁️ 69

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

Related articles

How to manage and display custom page Banner carousel in Anqi CMS?

In website operation, a beautiful page banner carousel is a key element to attract visitors' attention, convey important information, and enhance brand image.AnQiCMS provides a flexible and intuitive way to manage and display these visual contents, whether you want to set up a Banner for the homepage, a specific page, or a category page, it can be easily achieved.### Manage Custom Banner Carousel AnQi CMS allows you to set exclusive banners for different content types, mainly divided into banners for specific pages

2025-11-08

How does AnQi CMS filter and display content based on the document's Flag attribute (such as headline, recommended)?

In AnQiCMS (AnQiCMS) content management system, effectively organizing and displaying content is the key to enhancing website attractiveness and user experience.Among them, the Flag attribute (recommended attribute) function of the document, as if marking the content with a special 'mark', allows you to flexibly filter and highlight important or specific types of content according to your operational needs.What is the document Flag attribute? The document Flag attribute, also known as the recommendation attribute, is a content classification and display mechanism provided by AnQi CMS.

2025-11-08

How to add multi-dimensional parameter filtering function for the product list page in Anqi CMS and display the filtering results?

In modern e-commerce and content display websites, providing multi-dimensional parameter filtering functions for product lists has become a key factor in improving user experience and conversion rates.Visitors can quickly locate the products they need based on their own needs, not only saving time but also significantly improving the usability of the website.For users of AnQiCMS, implementing such a feature is not difficult. The built-in powerful functions and flexible template tags make the whole process intuitive and efficient.This article will delve into how to add multi-dimensional parameter filtering functions to the product list page in Anqi CMS

2025-11-08

How to display the current year or time in a specific format in AnQi CMS template?

In website operation, it is a common requirement to flexibly display the current year or format specific time, whether it is the automatic update of the year in the copyright statement or the clear display of the publication time on the article detail page.AnQiCMS provides two main ways to meet these needs, they are both simple to use and follow the elegant time handling of the Go language.### Method 1: Directly retrieve and display the current year or time (`{% now %}` tag) When you need to directly retrieve and display the current year or the current time down to the second in the template

2025-11-08

How to safely output rich text content containing HTML tags in Anqi CMS template?

In website operation, rich text content is widely used in articles, product introductions, and single-page scenarios due to its rich expression, such as inserting images, custom font styles, and tables.AnQi CMS as an efficient content management system also fully supports the editing and storage of various rich text content.However, rich text content, while bringing convenience, also hides a non-negligible security challenge - how to safely output this content containing HTML tags in templates to prevent potential cross-site scripting attacks (XSS)

2025-11-08

How to implement independent content management and unified display for multi-sites in AnQiCMS?

How to implement independent content management and unified display for multiple sites in AnQiCMS?In today's rapidly changing internet environment, many enterprises and content operators face the challenge of managing multiple websites.Whether it is to have multiple brands, product lines, or to create independent content portals for different markets and audiences, efficiency and convenience are always the key.The traditional approach is often to deploy a separate system for each website, which not only increases maintenance costs but also makes content management and data integration extremely complex.AnQiCMS provides an elegant and efficient solution

2025-11-08

How to customize the content model so that it can display different types of content in a unique way on the front-end page (such as articles, products)?

In Anqi CMS, the custom ability of the content model is one of its core advantages, which gives us great flexibility, allowing the website to break free from the traditional constraints of 'articles' and 'pages', and organize and display various types of information according to actual business needs.Whether it is a complex e-commerce product detail or a refined corporate case presentation, it can present unique style and functions on the frontend page through a custom content model.### Understanding the importance of content models A content model, simply put, is the "skeleton" or "blueprint" of the content on your website

2025-11-08

How to implement multilingual switching for website content and ensure that the user interface and article content are displayed correctly?

In today's globalized digital age, having a website that supports multiple languages is crucial for businesses to expand into international markets and improve user experience.AnQiCMS (AnQiCMS) is an efficient and flexible content management system that provides a powerful and easy-to-operate multilingual switching solution, ensuring that the user interface and article content of the website can be correctly displayed to users of different languages.### The Foundation of Multilingual Websites: AnQiCMS Multi-Site Management The core mechanism of AnQiCMS for multilingual switching is its unique **multi-site management** function

2025-11-08