thinkphp5.1使用ajax实现验证码功能,点击刷新

浏览:4310 发布日期:2018/06/25 分类:功能实现 关键字: thinkphp5.1 ajax 验证码 点击刷新
tp5.1通过ajax来实现验证码验证
功能如下:
首先使用Composer安装think-captcha扩展包:(注意这里要先使用命令指向到当前网站跟目录,我的是d:wamp/www/tp5)
composer require topthink/think-captcha
安装需要一定时间,完成后在根目录下的vendor/topthink/里会有一个think-captcha的文件夹,表示安装成功~
//控制器代码如下:
<?php
namespace app\index\controller;
use think\Controller;

class Index extends Controller
{
    public function index(){

        return $this->fetch();
          
    }

    public function varify()
    {
        
        $id=input('post.id');

  
        if( !captcha_check($id))
        {
            return json("验证失败");    
        }else{
            return json("验证码验证成功~");    
        }
                
        
         
    }
  
}

/***************************************************************/
//模板代码如下(这个模板是Index/index/index的)
<!DOCTYPE html>
<html>
<head>
    <title>index</title>
</head>
<body>


<img id="captcha_img" src="{:captcha_src()}"  onclick="refreshVerify()"/>

<input type="text" id="cs" value="">
<input type="button" name="" id="login">



<script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">

    function refreshVerify() {
        
        var ts=Date.parse(new Date())/1000;
        console.log(ts);
        $('#captcha_img').attr('src','/captcha?rand='+ts);//这里使用rand的是,如果改为id的话会导致在刷新验证码之后无法验证成功,我都唔知讲咩好 
    }
    
</script>

<script type="text/javascript">

    $("#login").click(function(){
         var cs = $('#cs').val();
        $.ajax({
            type:"POST",
            url:"{:url('Index/index/varify')}",    
            dataType:"json",
            data:{"id":cs},
            success:function(data){
                
                alert(data);
                
                },
                error:function(){
                        //抛出异常
                        alert('error');    
            }
        });

    })
</script>



</body>
</html>
最后没有啦,不懂的加我1933,987,037,欢迎交流指点
评论( 相关
后面还有条评论,点击查看>>