In Anqi CMS, we often encounter scenarios where users need to submit information, such as message boards, comment sections, and so on.To prevent malicious flooding and spam, introducing a captcha mechanism is an essential step.When you enable the message captcha feature in AnQiCMS and try to integrate it into a website template, you may be curious about where these HTML and JavaScript codes should be placed to work properly.As an experienced website operations expert, I am willing to give you a detailed explanation of this process.

The operation principle and necessity of the captcha mechanism

Firstly, understanding the operation principle of CAPTCHA is crucial for correct deployment.The AnQiCMS留言验证码 is a client-server collaborative mechanism.When the user visits the message page, the front-end page will request a captcha image and a unique captcha ID.After the user fills in the message and enters the verification code, this information, along with the verification code ID, is submitted to the server.The server will compare the verification code ID with the user's input to determine the validity of the comment.

This mechanism effectively blocks malicious attacks from automated programs, maintains the purity of website content and user experience.

Backend configuration: Enabling the captcha feature is a prerequisite

Before adding the captcha code to the front-end template, please make sure that you have enabled the comment captcha feature in the AnQiCMS backend.This is the basis on which the entire captcha mechanism can work normally.Generally, you can find the relevant options in the background "Function Management" or "Global Settings" and check them to enable.If the background feature is not enabled, even if the front-end code is deployed correctly, the captcha cannot be displayed or verified normally.

Front-end integration: Precise placement of code

Once the background captcha feature is enabled, the next step is to elegantly integrate HTML and JavaScript code into your website template. According to the AnQiCMS template design principles, the comment or message form usually has a dedicated template file for rendering, for example, it may be in the template directory structure that isguestbook/index.htmlorcomment/list.html(or in the case of flat mode'sguestbook.html)

The placement of HTML code: key elements within the form

The HTML element for the captcha must be placed in the message or comment section<form>Inside the tag, as they are submitted along with the user's message content as part of the form data. You need to add two core elements: a hidden input box to store the captcha ID, a text input box for the user to enter the captcha, and a<img>The label is used to display the captcha image.

In particular, these HTML elements should be placed near other input fields on your comment form (such as username, comment content, etc.) to maintain the logical integrity of the form. A common practice is to place them in adivWithin the container, for layout and style control, for example:

<div style="display: flex; align-items: center; margin-bottom: 15px;">
  <!-- 存储验证码ID的隐藏输入框 -->
  <input type="hidden" name="captcha_id" id="captcha_id">
  <!-- 用户输入验证码的文本框 -->
  <input type="text" name="captcha" required placeholder="请填写验证码" class="layui-input" style="flex: 1; margin-right: 10px;">
  <!-- 显示验证码图片的img标签 -->
  <img src="" id="get-captcha" style="width: 120px; height: 40px; cursor: pointer; border: 1px solid #ccc;" alt="验证码" title="点击刷新验证码"/>
</div>

here,#captcha_idand#get-captchaIs a DOM element that JavaScript code needs to operate on, their IDs must be consistent.

The placement of JavaScript code: after the DOM is loaded

The responsibility of JavaScript code is to interact with the backend API, retrieve and update the captcha image and its ID. This code needs to ensure that it references the HTML element (i.e.,#captcha_idand#get-captchaExecute after the DOM tree has been loaded.

The recommended position is immediately after the CAPTCHA HTML code, or in a script block that runs after the page has finished loading (for example, placed in</body>before a tag, or useDOMContentLoadedEvent listener). If it is only used for a message board, embedding it directly into theguestbook/index.html(orguestbook.htmltemplate's corresponding position is the most direct and effective way.

Original JavaScript code example using the native Fetch API:

<script>
  // 绑定点击事件,当点击验证码图片时刷新
  document.getElementById('get-captcha').addEventListener("click", function () {
    fetch('/api/captcha') // 请求后端API获取新的验证码
      .then(response => response.json())
      .then(res => {
        // 更新隐藏输入框中的验证码ID
        document.getElementById('captcha_id').value = res.data.captcha_id;
        // 更新验证码图片源
        document.getElementById('get-captcha').src = res.data.captcha;
      })
      .catch(err => console.error("Error fetching captcha:", err));
  });
  // 页面加载后立即触发一次点击,以显示初始验证码
  document.getElementById('get-captcha').click();
</script>

If you use jQuery in your project, you can also use a more concise jQuery syntax:

<script>
  $(function() { // 确保DOM加载完毕后执行
    // 绑定点击事件,当点击验证码图片时刷新
    $('#get-captcha').on("click", function () {
      $.get('/api/captcha', function(res) {
        // 更新隐藏输入框中的验证码ID
        $('#captcha_id').val(res.data.captcha_id);
        // 更新验证码图片源
        $('#get-captcha').attr("src", res.data.captcha);
      }, 'json')
      .fail(function(jqXHR, textStatus, errorThrown) {
        console.error("Error fetching captcha:", textStatus, errorThrown);
      });
    });
    // 页面加载后立即触发一次点击,以显示初始验证码
    $('#get-captcha').click();
  });
</script>

This script will perform the following tasks:

  1. Bind events:Listen to the click event of the verification code image, every time the image is clicked, it will send a request to/api/captchasend a request.
  2. Get data:Receive the verification code ID and image URL returned by the backend.
  3. Update DOM:Fill the new captcha ID into the hiddencaptcha_idinput box and update the captcha imagesrcproperty to the new image URL.
  4. Initial loading:After the page is loaded, an automatic click event is triggered to ensure that the captcha is displayed to the user during their first visit to the page.

The level of reference of the template file.

AnQiCMS templates usually adopt the inheritance mechanism(extends)and inclusion(include)mechanisms. The template for the message page(such asguestbook/index.html)may inherit from onebase.html, and may pass through{% include 'partial/form-captcha.html' %}This way to introduce the captcha code snippet.

  • The most direct way:Place the above HTML and<script>tags directly in.guestbook/index.htmlorguestbook.htmlThis comment form is located in the template file. This is the simplest and least likely to go wrong method, especially when the captcha is only used on specific pages.
  • Modular approach (throughinclude):To keep the template neat, you can encapsulate the captcha's HTML and JavaScript into a separate fragment file, such aspartial/captcha.html, then inguestbook/index.htmlpass through{% include 'partial/captcha.html' %}Introduce this method. This approach is very useful when the captcha logic is complex or needs to be reused across multiple forms. Make sure topartial/captcha.htmlthe position where it is introduced is within the form.

In summary, place the HTML and JavaScript code of AnQiCMS comment captchawithin the template file that carries the comment or review form,Make sure JavaScript executes after the relevant HTML elements load, it is**practice.At the same time, don't forget to enable the corresponding captcha function in the background, which is a prerequisite for ensuring its normal operation.By following these steps, your AnQiCMS website can have a safe and smooth留言互动 environment.


Frequently Asked Questions (FAQ)

1. I have already followed