基于ajax的模拟登陆验证

输入账号密码,进行ajax请求,成功调转其他页面,失败在登陆后显示错误信息。

urls.py

from django.contrib import admin
from django.urls import path
from app01 import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/',views.index),
    path('login/',views.login),
]

views.py

简单模拟,不使用数据库

from django.shortcuts import render,HttpResponse

# Create your views here.
import json
def index(request):
    return render(request,'index.html')
def login(request):
    print(request.POST)
    user = request.POST['user']
    password = request.POST['password']
    res = {'user':None,'msg':None}
    if user == 'admin' and password == '123456':
        res['user'] = user
    else:
        res['msg'] = 'username or password wrong !'
    return HttpResponse(json.dumps(res))

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.4.min.js"></script>
</head>
<body>
<form>
    用户名 <input type="text" id="user">
    密码 <input type="password" id="password">
    <input type="button" value="登录" class="login_btn"><span class="error"></span>
</form>

</body>

<script>
    //登录验证
    $('.login_btn').click(function () {
        $.ajax({
            url:'/login/',
            type:'post',
            data:{
                'user':$("#user").val(),
                'password':$("#password").val(),
            },
            success:function (data) {
                console.log(data);//json字符串
                console.log(typeof data);
                var data = JSON.parse(data); //反序列化
                console.log(data);//json字符串
                console.log(typeof data);
                if (data.user){
                    location.href='https://www.mi.com/'
                }else {
                    $('.error').html(data.msg).css({'color':'red','margin-left':'10px'})
                }
            }

        })
    })
</script>
</html>

结果(错误输入)

在这里插入图片描述

注意:
怎样将Python的数据传递给js使用是一个非常重要的知识点。
两种语言都支持json,在Python中json的格式就像是字典一样,但是在js中,json格式要经过反序列化转为object类型,才能被灵活的使用。
所以利用Python中的json.dumps()方法,将字典类型的数据序列化为字符串传递到js中,js中JSON.parse()方法,将数据反序列化为object类型的数据,如果Python中序列化的数据为列表类型,js反序列化为数组类型。

view.py序列化数据

在这里插入图片描述在这里插入图片描述

index.html反序列化数据

在这里插入图片描述在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章