Elegantly obtain the specific error prompt information after the captcha verification fails on the AnQiCMS front-end
As an experienced website operations expert, I am well aware of the importance of user experience in website operations.When a user performs an operation on your AnQiCMS website (such as leaving a message, commenting, registering, etc.), if they encounter a captcha verification failure, a clear and immediate error message can greatly reduce the user's frustration and guide them to correctly complete the operation.How can you accurately obtain and display the specific error prompts after the captcha verification fails on the AnQiCMS frontend?Today, let's delve into it in depth.
Understand the captcha mechanism of AnQiCMS
First, let's briefly review the normal workflow of AnQiCMS front-end captcha. According to the documentation we provide, especiallytag-/anqiapi-other/167.htmlIn Chinese, we can see that AnQiCMS usually interacts with the backend API through frontend JavaScript to obtain and display the captcha.
When your web page is fully loaded, or the user clicks to refresh the captcha, the front-end will send a request to the AnQiCMS backend, usuallyGET /api/captcha. The backend will generate a response containingcaptcha_idThe captcha unique identifier andcaptchaThe JSON data of the captcha image Base64 encoding or image URL. The front-end JavaScript will receive these data and willcaptcha_idStored in a hidden field andcaptchadisplayed to the user.
At this stage, we mainly handle the display of captcha. And our focus today is on what happens after the user fills in the captcha and submits the form.When the verification fails.How to get specific prompts.
The error message after the verification code fails to be verified
The actual verification of the captcha occurs when the user submits the form to the backend. When the user fills in the captcha and clicks the submit button, the front end will send the form data (including the captcha contentcaptchaand captcha identifiercaptcha_id) sent to the backend for processing. If the backend finds a mismatch or other error during the captcha verification, it needs to return these specific error messages to the frontend.
AnQiCMS handles such form submissions by usually providing a flexible response mechanism. Intag-/anqiapi-other/158.htmlandtag-/anqiapi-other/162.htmlwe see a key parameter in the documents related to form submissions.return. By setting at the time of form submissionreturnthe value of the parameter, we can control the data format returned by the backend:
return=html(default): If not setreturnor set tohtmlThe backend usually returns a complete HTML page, which may be the current page with error messages or redirected to an error message page.In this case, the front-end needs to parse the entire HTML page to extract error information, which is usually complex and has a poor user experience.return=json(Recommended)It is strongly recommended to set when submitting the form for the convenience of front-end JavaScript processingreturn=jsonThis way, even if the verification fails, the backend will return a structured JSON object, which includescode(error code),msg(specific error message) and other fields.
Therefore, the core of obtaining the specific prompt information after the verification code fails is:Use asynchronous requests (AJAX) to submit the form and explicitly require the backend to return JSON formatted error messages.
Implementation steps
- Prevent the default form submission behavior:Use JavaScript to intercept the form's
submitevent to prevent the browser from performing traditional page jump submission. - Build asynchronous requests:By
fetchThe API or jQuery's$.ajaxmethod, manually construct an HTTPPOSTRequest, send the form data to the backend. - include
return=jsonparameters:In the request'sbodyorURLspecify clearly.return=jsonParameter. - Parse the backend JSON response:After receiving the JSON data returned by the backend, check the
codeField to determine whether the operation was successful and passmsgField to obtain specific error prompt information. - Front-end error display:To get
msgInformation is dynamically displayed to the user, for example, by showing red text prompts below the captcha input box or by using pop-up alerts.
Example code (taking the message form as an example)
Assuming you have followed the instructionstag-/anqiapi-other/167.htmlintegrated the captcha and the form HTML structure is similartag-/anqiapi-other/162.html:
`html
// === 验证码图片获取逻辑(来自tag-/anqiapi-other/167.html) ===
const captchaImage = document.getElementById('get-captcha');
const captchaIdField = document.getElementById('captcha_id');
const captchaErrorSpan = document.getElementById('captchaError');
function fetchNewCaptcha() {
fetch('/api/captcha')
.then(response => response.json())
.then(res => {
if (res.code === 0 && res.data) {
captchaIdField.value = res.data.captcha_id;
captchaImage.src = res.data.captcha;
captchaErrorSpan.style.display = 'none'; // 隐藏之前的错误信息
} else {
// 如果获取验证码图片本身失败
captchaErrorSpan.textContent = res.msg || '获取验证码失败,请刷新页面。';
captchaErrorSpan.style.display = 'block';
}
})
.catch(err => {
console.error('获取验证码图片时发生网络错误:', err);
captchaErrorSpan.textContent = '网络错误,无法获取验证码。';
captchaErrorSpan.style.display = 'block';
});
}
captchaImage.addEventListener("click", fetchNewCaptcha);
document.addEventListener("DOMContentLoaded", fetchNewCaptcha); // 页面加载时自动获取一次
// === 表单提交及错误信息处理逻辑 ===