As an experienced website operations expert, I know the importance of user experience in the success of a website.In today's fast-paced online environment, users have increasingly high expectations for page loading speed and smooth interaction.The traditional form submission method often leads to page refreshes, which not only interrupts the user's operational flow but may also cause unnecessary waiting due to network latency, thereby affecting user satisfaction.
Fortunately, with the continuous development of front-end technology, we can use Ajax (Asynchronous JavaScript and XML) to asynchronously submit data, completing form submission without refreshing the page, which significantly improves the user experience.Today, let's delve into how to elegantly implement the Ajax asynchronous submission of the comment form on the frontend of AnQiCMS.
Farewell to waiting: Gracefully implement the Ajax asynchronous submission of the留言表单in AnQiCMS frontend
AnQiCMS is the preferred choice for many enterprises due to its efficiency, customizability, and SEO-friendliness.Its flexible template engine and rich tag functions provide great convenience for front-end developers.The comment form acts as an important bridge for interaction between the website and users. Using Ajax asynchronous submission not only optimizes the user experience but also reduces server pressure and improves data processing efficiency.
Preparation: Understand the operation mechanism of the 留言表单in AnQiCMS
Before implementing Ajax submission on the front-end, we need to first understand how the AnQiCMS message form works on the back-end. According to the AnQiCMS documentation, message form data is submitted to/guestbook.htmlThis URL. It is noteworthy that AnQi CMS supports one.returnTo control the data format of the server's response.For Ajax submissions, we typically expect the server to return data in JSON format so that front-end JavaScript can easily parse and process it.
AnQi CMS template tags{% guestbook fields %}Can dynamically generate the comment form fields for backend configuration. These fields include but are not limited to:
user_name: Name of the commentorcontact: Contact informationcontent: Comment content- [en]In addition, various fields you customize in the background.
[en]Moreover, if the comment captcha feature is enabled in the background, the form must also includecaptcha_idandcaptchaTwo fields, as well as an image element for refreshing the captcha.
Construct the HTML structure for the front-end message form.
Firstly, in your company CMS template file (for example,guestbook/index.htmlor your custom message page template) to create a basic HTML form. For convenience in JavaScript accessing form elements, it is recommended to add aidThe key is to ensure that all input fields have the correctnameattributes, thesenameattributes must match the field names expected by the AnQiCMS backend.
Here is an example of an HTML form structure that includes dynamic fields and a captcha:
<form id="guestbookForm" method="post" action="/guestbook.html">
<!-- 动态生成的留言字段 -->
{% guestbook fields %}
{% for item in fields %}
<div class="form-group">
<label for="{{ item.FieldName }}">{{ item.Name }}{% if item.Required %}<span class="text-danger">*</span>{% endif %}</label>
<div>
{% if item.Type == "text" or item.Type == "number" %}
<input type="{{ item.Type }}" name="{{ item.FieldName }}" id="{{ item.FieldName }}"
{% if item.Required %}required{% endif %} placeholder="{{ item.Content }}" autocomplete="off"
class="form-control">
{% elif item.Type == "textarea" %}
<textarea name="{{ item.FieldName }}" id="{{ item.FieldName }}"
{% if item.Required %}required{% endif %} placeholder="{{ item.Content }}" rows="5"
class="form-control"></textarea>
{% elif item.Type == "radio" %}
{% for val in item.Items %}
<input type="{{ item.Type }}" name="{{ item.FieldName }}" value="{{ val }}" id="{{ item.FieldName }}-{{ loop.index }}">
<label for="{{ item.FieldName }}-{{ loop.index }}">{{ val }}</label>
{% endfor %}
{% elif item.Type == "checkbox" %}
{% for val in item.Items %}
<input type="{{ item.Type }}" name="{{ item.FieldName }}[]" value="{{ val }}" id="{{ item.FieldName }}-{{ loop.index }}">
<label for="{{ item.FieldName }}-{{ loop.index }}">{{ val }}</label>
{% endfor %}
{% elif item.Type == "select" %}
<select name="{{ item.FieldName }}" id="{{ item.FieldName }}" class="form-control">
{% for val in item.Items %}
<option value="{{ val }}">{{ val }}</option>
{% endfor %}
</select>
{% endif %}
</div>
</div>
{% endfor %}
{% endguestbook %}
<!-- 验证码部分 (如果后台开启) -->
<div class="form-group captcha-section">
<label>验证码<span class="text-danger">*</span></label>
<div class="input-group">
<input type="hidden" name="captcha_id" id="captchaId">
<input type="text" name="captcha" id="captchaInput" required placeholder="请输入验证码" class="form-control captcha-input">
<img src="" id="captchaImage" alt="验证码" class="captcha-img">
</div>
</div>
<!-- 重要的隐藏字段:告诉AnQiCMS我们想要JSON响应 -->
<input type="hidden" name="return" value="json">
<div class="form-group">
<button type="submit" id="submitBtn" class="btn btn-primary">提交留言</button>
<button type="reset" class="btn btn-secondary">重置</button>
</div>
</form>
<div id="responseMessage" class="mt-3"></div>
<script>
// 验证码刷新逻辑 (来自tag-captcha.md文档)
function refreshCaptcha() {
fetch('/api/captcha')
.then(response => response.json())
.then(res => {
if (res.code === 0) {
document.getElementById('captchaId').value = res.data.captcha_id;
document.getElementById('captchaImage').src = res.data.captcha;
} else {
console.error('Failed to get captcha:', res.msg);
}
})
.catch(err => console.error('Error fetching captcha:', err));
}
// 页面加载时初始化验证码
document.addEventListener('DOMContentLoaded', refreshCaptcha);
// 点击验证码图片时刷新
document.getElementById('captchaImage').addEventListener('click', refreshCaptcha);
</script>
Implementing JavaScript logic for Ajax asynchronous submission
Next, we will use JavaScript (here using the native one,fetchUsing an API as an example, it is more modern and does not require libraries to handle form submission events. The core idea is to prevent the