Ajax提交表單時驗證碼自動驗證 php后端驗證碼檢測
本文通過源碼展示如何實現(xiàn)表單提交前,驗證碼先檢測正確性,不正確則不提交表單,更新驗證碼。
1、前端代碼 index.html
<!DOCTYPE html>
<html>
<head>
<title>驗證碼提交自驗證</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Language" content="zh-CN" />
</head>
<body>
<form action="doPost.php" method="POST">
<div class="row">
<label for="username">用戶名</label>
<input type="text" name="username" id="username" />
</div>
<div class="row">
<label for="mod-captcha-code">驗證碼</label>
<input name="code" id="mod-captcha-code" size="6" class="zjcaptcha" style="width:80px" type="text"/>
<img class="code-img" style="height:30px;width:80px;" src="createcode.php?t=0" onclick="this.src=this.src.substring(0,this.src.indexOf('?')+1)+Math.random();return false;" />
<script type="text/javascript" src="http://www.zjmainstay.cn/jquery/jquery-1.8.2.min.js"></script>
<div class="yzmtips" style="color:red"></div>
</div>
<div class="row">
<input type="submit" value="提交" class="submitBtn"/>
</div>
</form>
<script>
(function($){
$(document).ready(function(){
$(".submitBtn").click(function() {
var obj = $(this);
$.ajax({
url:'checkcode.php',
type:'POST',
data:{code:$.trim($("input[name=code]").val())},
dataType:'json',
async:false,
success:function(result) {
if(result.status == 1) {
obj.parents('form').submit(); //驗證碼正確提交表單
}else{
$(".code-img").click();
$(".yzmtips").html('驗證碼錯誤!');
setTimeout(function(){
$(".yzmtips").empty();
},3000);
}
},
error:function(msg){
$(".yzmtips").html('Error:'+msg.toSource());
}
})
return false;
})
});
})(jQuery);
</script>
</body>
</html>
2、后端驗證碼檢測 checkcode.php
<?php
/**
* 用戶驗證碼驗證文件
* @Author:Zjmainstay
* @version : 1.0
* @creatdate: 2013-10-4
*/
session_start();
echo json_encode(array('status'=>(int)($_SESSION["CHECKCODE"] == $_POST['code'])));
exit;
源碼下載地址:Ajax實現(xiàn)提交表單時驗證碼自動驗證
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Yii學習總結(jié)之數(shù)據(jù)訪問對象 (DAO)
本文是YII學習總結(jié)系列文章的第二篇,主要向我們介紹了數(shù)據(jù)訪問對象(DAO),十分的詳細,有需要的小伙伴參考下2015-02-02
thinkphp微信開之安全模式消息加密解密不成功的解決辦法
使用thinkphp官方的WeChat包,使用不同模式可以成功,但是安全模式就是不行,現(xiàn)將分析解決結(jié)果做下記錄,對thinkphp加密解密相關(guān)知識感興趣的朋友參考下2015-12-12
Laravel框架定時任務(wù)2種實現(xiàn)方式示例
這篇文章主要介紹了Laravel框架定時任務(wù)2種實現(xiàn)方式,結(jié)合實例形式較為詳細的分析了Laravel框架定時任務(wù)相關(guān)實現(xiàn)方法及操作注意事項,需要的朋友可以參考下2018-12-12
使用PHP和JavaScript判斷請求是否來自微信內(nèi)瀏覽器
這篇文章主要介紹了使用PHP和JavaScript判斷請求是否來自微信內(nèi)瀏覽器,包括在手機端的程序上使用微信的分享JS腳本的方法,需要的朋友可以參考下2015-08-08
php中使用array_filter()函數(shù)過濾空數(shù)組的實現(xiàn)代碼
這篇文章主要介紹了php中使用array_filter()函數(shù)過濾空數(shù)組的實現(xiàn)代碼,這是瀏覽PHP手冊時無意發(fā)意的一個有意思的array_filter()函數(shù)用法,需要的朋友可以參考下2014-08-08

