//html表单
<form action="{:U('Index/getUser')}" method="post">
admin_user:<input type="text" name="txtName"><br/>
admin_password:<input type="password" name="txtPwd"><br/>
验证码:<input size="8" name="verify_code">
<img src="{:U('Index/verify_code')}" id="code" οnclick="this.src=this.src+'?' +Math.random(); ">//此src指向的是think自带的验证码方法,而且可以点击切换验证码
<a href="javascript:void(0);" οnclick="document.getElementById('code').src='{:U('Index/verify_code')}' ">看不清?换一张!</a><br>//点击切换验证码
<input type="submit" value="登录" id="btnSend">
</form>
//控制器中的验证码方法,生成img图
public function verify_code(){
$config=array(
'fontSize' => 16, //验证码字符大小
'length' => 4, //验证码位数
'useImgBg' => false,
'imageW' => 160,
'imageH' => 40,
'useZN' => false,
);
$Verify = new \Think\Verify($config);
$Verify->entry();
}
//在控制器中登陆方法中添加验证验证码对错代码
$code=strtolower(trim($_POST['verify_code']));
$Verify= new \Think\Verify();
if (! $Verify->check($code)) {
$this->error('验证码错误');
}
//在Common公共方法中创建function.php文件
function check_code($code,$id=''){
$Verify = new \Think\Verify();
$Verify->reset=false;
return $Verify->check($code,$id);
}
//我用了ajax方法来继续验证对错
//通过blur来移动验证
$(function(){
$("input[name='verify_code']").blur(function(){
var cont={verify_code:$(this).val()};
var txtCode=$(this);
txtCode.next("span").remove();
$.ajax({
url:'__CONTROLLER__/ajax_check',
type:'POST',
data:cont,
dataType:'json',
success:function(data){
if (data.code) {
ver_code=true;
};
txtCode.after("<span>"+data.msg+"</span>");
},
erro:function(){
alert(err.status+":"+err.statusText);
},
});
});
});
//在控制器中写ajax的方法
public function ajax_check(){ $code=strtolower(trim($_POST['verify_code'])); $data=array('code'=>0,'msg'=>"验证码错误!"); if ( check_code($code) ) { $data=array('code'=>1,'msg'=>"验证码正确!"); } $this->ajaxReturn($data); }
//错误显示
//正确显示