在網(wǎng)站留言、評論中需要開啟驗證碼的時候,可以按如下操作來處理:
<div style="display: flex; clear: both">
<input type="hidden" name="captcha_id" id="captcha_id">
<input type="text" name="captcha" required placeholder="請?zhí)顚戲炞C碼" class="layui-input" style="flex: 1">
<img src="" id="get-captcha" style="width: 150px;height: 56px;cursor: pointer;" />
<script>
document.getElementById('get-captcha').addEventListener("click", function (e) {
fetch('/api/captcha')
.then(response => {
return response.json()
})
.then(res => {
document.getElementById('captcha_id').setAttribute("value", res.data.captcha_id)
document.getElementById('get-captcha').setAttribute("src", res.data.captcha)
}).catch(err =>{console.log(err)})
});
document.getElementById('get-captcha').click();
</script>
</div>
如果你的網(wǎng)站使用了jQuery,則<script></script>
部分可以使用jquery的寫法:
<script>
// jquery 調用方式
$('#get-captcha').on("click", function (e) {
$.get('/api/captcha', function(res) {
$('#captcha_id').attr("value", res.data.captcha_id)
$('#get-captcha').attr("src", res.data.captcha)
}, 'json')
})
$('#get-captcha').click();
</script>
至此,你的留言或評論就開啟了驗證碼驗證功能,用戶留言就需要輸入驗證碼驗證了。