在網(wǎng)站留言、評(píng)論中需要開(kāi)啟驗(yàn)證碼的時(shí)候,可以按如下操作來(lái)處理:
<div style="display: flex; clear: both">
<input type="hidden" name="captcha_id" id="captcha_id">
<input type="text" name="captcha" required placeholder="請(qǐng)?zhí)顚?xiě)驗(yàn)證碼" 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的寫(xiě)法:
<script>
// jquery 調(diào)用方式
$('#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>
至此,你的留言或評(píng)論就開(kāi)啟了驗(yàn)證碼驗(yàn)證功能,用戶留言就需要輸入驗(yàn)證碼驗(yàn)證了。