python—day65 登陆注册Ajax实例,Django的Form组件的使用

Ajax写登陆注册实例:

第一步:去数据库创建一些数据,username 和 password;
第二步:urls里面添加登陆注册路由;
第三步:views里面写register和login:
通过jQuery的光标移除事件,把input里面的数据存成JSON数据格式,然后通过ajax异步发送post请求到服务端,

服务端通过ORM去数据库验证是否存在,编写逻辑,然后把结果打包成JSON格式的数据返回到前端;然后再进行前端的处理;

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录示例</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.min.css">
    <style>
        .login-box {
            margin-top: 100px;
        }

        body {
            background-color: #eeeeee;
        }
        .error{
            color: mediumvioletred;
        }
    </style>
</head>
<body>

<div class="container">
    <div class="row">
        <div class="col-md-4 col-md-offset-4 login-box">
            <h1 class="text-center">请登录</h1>
{#            <form class="form-horizontal" action="/login/" method="post">#}
                {% csrf_token %}
                <div class="form-group">
                    <label for="inputEmail3" class="col-sm-3 control-label">用户名</label>
                    <div class="col-sm-9">
                        <input type="text" name="username" class="form-control" id="inputEmail3" placeholder="用户名">
                        <span class="help-block error" id="u1"></span>
                    </div>
                </div>
                <div class="form-group">
                    <label for="inputPassword3" class="col-sm-3 control-label">密码</label>
                    <div class="col-sm-9">
                        <input type="password" name="pwd" class="form-control" id="inputPassword3" placeholder="密码">
                        <span class="help-block error" id="p1"></span>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-offset-3 col-sm-9">
                        <div class="checkbox">
                            <label>
                                <input type="checkbox"> 记住我
                            </label>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-offset-3 col-sm-9">
                        <button id="b1" class="btn btn-primary btn-block">登录</button>
                    </div>
                </div>

        </div>
    </div>
</div>
<script src="/static/jquery-3.3.1.min.js"></script>
<script src="/static/setupAjax.js"></script>
<script>
    $("input").on("focus", function () {
        $(this).next().text("").parent().parent().removeClass("has-error");
    });

    $('#b1').click(function () {
        var data = {username:$('input[name=username]').val(),pwd:$('input[name=pwd]').val()};
        console.log(data);
        $.ajax({

            url:'/login/',

            type:'post',

            data:data,

            success:function (data) {

                if (data.code){
                    $('#u1').text(data.mes_error);
                    $('#p1').text(data.mes_error);
                }else{
                    location.href = data.data
                }

            }
        })
    });

</script>
</body>
</html>
View Code

views.login

def login(request):
    if request.method == 'POST':
        ret = {"code": 0}
        username = request.POST.get('username')
        # print(username)
        pwd = request.POST.get('pwd')
        # print(pwd)
        ok = models.User.objects.filter(name=username, pwd=pwd)
        # print(ok)
        if not ok:
            ret["code"] = 1
            ret["mes_error"] = "用户名或者密码错误!"
        else:
            ret["data"] = "http://www.luffycity.com"
        return JsonResponse(ret)
    return render(request, 'login.html')
View Code

register.html

<!doctype html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
<style>
    .err{
        color:red;
    }
</style>

</head>
<body>

{% csrf_token %}



<p>用户名:<input id="i1" type="text">
<span class="err" id="err1"></span>
</p>
<p>密码:<input id="i2" type="password"></p>
<button id="b1" >注册</button>


<script src="/static/jquery-3.3.1.min.js"></script>
<script src="/static/setupAjax.js"></script>
<script>
    $("#i1").blur(function () {
        $("#err1").text("");
        var value = $(this).val();
        $.ajax({
            url: '/check_name/',
            type: 'post',
            data: {value:value},
            success:function (data) {
                if (data.code){
                    $("#err1").text(data.mes_err);
                }
            }
        })


    })


</script>

</body>
</html>
View Code

views.register

def register(request):
    return render(request, 'register.html')


def check_name(request):
    if request.method == 'POST':
        value = request.POST.get('value')
        print(value)
        result = models.User.objects.filter(name=value)
        ret = {'code': 0}
        if result:
            ret['code'] = 1
            ret['mes_err'] = "用户名已存在"

        return JsonResponse(ret)
View Code

猜你喜欢

转载自www.cnblogs.com/kermitjam/p/9238561.html