有3個檔案:
authcode.php-----驗證碼的產生php檔案
authcode.html-----前台顯示頁面
dealauthcode.php-----ajax提交到的幕後處理判斷驗證碼是否正確的處理頁面
*/
?>
前台調用驗證碼代碼
代碼如下 |
複製代碼 |
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html xmlns="http://www.111cn.net/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>驗證碼ajax驗證</title> <style type="text/css教程"> *{ font-size:12px;} a{ text-decoration:none;} a:hover{ text-decoration:underline; color:red;} </style> <script language="網頁特效" src="http://code.jquery.com/jquery-1.4.2.min.網頁特效"></script> <script language="網頁特效"> $(document).ready(function(){ /*----------------看不清楚,換張圖片-----------*/ $("#chang_authcode_btn").click(function(){ var authcode_url = "authcode.php?t="+math.random(0,1); $("#authcode_img").attr('src',authcode_url); }); /*----------------檢測驗證碼-----------*/ $("#authcode").bind({ 'focusin':function(){ /** *得到焦點 *我將img圖片移除,若只改變src為' *'的話,在ie下會呈現出一個無圖片的小圖片, *所以我這裡選擇直接把img元素移除 */ $(this).next('label').children('img').remove(); $(this).next('label').children('span').text(''); }, 'focusout':function(){ /** *失去焦點 *這裡要做的事情主要有下列幾個: *(1)先用網頁特效驗證使用者輸入的驗證是不是4位合法的字元,正則匹配 *(2)如果正則匹配失敗(不是合法的4位字元),在更新次驗證碼圖片(也就是再觸發一次"看不清楚"的a標籤的點擊事件) */ var input_authcode = $(this).val(); var authcode_regex = new regexp('^[a-z0-9]{4}','i'); if(!authcode_regex.test(input_authcode)){//不是合法的4位字串,顯示錯誤資訊給使用者 $(this).next('label').prepend("<img src='input_error.gif'/>");//加上錯誤表徵圖 $(this).next('label').children('span').text('輸入的驗證碼格式錯誤!');//加上錯誤提示資訊 $("#chang_authcode_btn").trigger('click');//再次重新整理圖片 }else{//ajax伺服器驗證,就是把使用者的輸入的驗證碼提交到伺服器上的某個驗證頁面來處理! $.get('dealauthcode.php',{authcode:input_authcode},function(check_result){ if(check_result=='mis_match'){//伺服器驗證沒通過 $("#authcode").next('label').prepend("<img src='input_error.gif'/>");//加上錯誤表徵圖 $("#authcode").next('label').children('span').text('驗證碼輸入錯誤!');//加上錯誤提示資訊 $("#chang_authcode_btn").trigger('click');//再次重新整理圖片 }else{//伺服器驗證通過了 $("#authcode").next('label').prepend("<img src='input_ok.gif'/>");//加上正確表徵圖 $("#authcode").next('label').children('span').text('驗證碼輸入正確!');//加上正確提示資訊 } }); } } }); }); </script> </head> <body> <div > <div><img id="authcode_img" src="authcode.php" /> <a id="chang_authcode_btn" style="cursor:pointer">看不清楚?換一張!</a></div> <div>驗證碼:<input id="authcode" type="text" size="20" /><label><span class="error_msg"></span></label></div> </div> </body> </html> |
dealauthcode.php-----ajax提交到的幕後處理判斷驗證碼是否正確的處理頁面
代碼如下 |
複製代碼 |
<?php session_start(); $authcode = $_get['authcode']; //這裡的$_session['authcode']是在驗證碼authcode頁面產生的 if(strtoupper($authcode)!= $_session['authcode']){ echo 'mis_match'; } ?>
|