傳統驗證碼頁面一載入就送出圖片請求,容易造成不必要的流量與快取問題。這個範例換個思路:使用者把游標移進輸入框時,才動態產生驗證碼圖片,並且可以點擊圖片隨時刷新。
get_Code()。<img>,網址後方帶上 ?t=隨機數。<script language="javascript">
/* 顯示認證碼 */
function get_Code() {
var Dv_CodeFile = "Dv_GetCode.asp";
if (document.getElementById("imgid")) {
document.getElementById("imgid").innerHTML =
'<img src="' + Dv_CodeFile + '?t=' + Math.random() + '" alt="點擊刷新驗證碼" style="cursor:pointer;border:0;vertical-align:middle;height:18px;" onclick="this.src=\'' + Dv_CodeFile + '?t=\'+Math.random()" />';
}
}
</script>
<form name="form" method="post" action="index.asp">
<tr>
<td style="width:100px; text-align:right">驗證碼:</td>
<td style="width:150px; text-align:left">
<p>
<input type="text" name="code" id="code" size="4" maxlength="4" tabindex="6"
onfocus="get_Code(); this.onfocus=null;"
onkeyup="dv_ajaxcheck('checke_dvcode','code');" />
<span id="imgid" style="color:red">點擊獲取驗證碼</span>
<span id="isok_code"></span>
</p>
<input name="cur_action" type="hidden" value="add">
<input name="提交" type="submit" id="提交">
</td>
</tr>
</form>
<%
if request("cur_action") = "add" then
code = Request.Form("code")
if code = empty then
response.write "<script>alert('請輸入驗證碼!');history.go(-1);</script>"
Session("GetCode") = empty
response.End()
elseif lcase(code) <> lcase(Session("GetCode")) then
response.write "<script>alert('您輸入驗證碼出錯!');history.go(-1);</script>"
Session("GetCode") = empty
response.End()
else
Response.Write "<script>alert('登陸成功');history.back();</script>"
response.End()
end if
end if
%>
this.onfocus = null:只觸發一次,避免每次聚焦都重新產生圖片而打亂使用者已輸入的內容。lcase() 比對可讓驗證碼不區分大小寫,對使用者友善很多。實作時記得把 dv_ajax.js 與 Dv_GetCode.asp 換成你自己的檔案路徑。若改用其他後端語言,整體邏輯(Session 存答案、隨機參數防快取、失敗即清空)都可以直接沿用。