1. 程式人生 > >基於Ajax的登入驗證

基於Ajax的登入驗證

前端index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="/static/js/jquery-3.3.1.js"></script>
    <title>Title</title>
</head>
<body>
<form>
   <p>使用者名稱:<input type="te ixt" id="name"></p>
   <p>密碼:<input type="text"d="pwd"></p>
{#    不行 --會觸發form表單的提交#}
{#    <input type="submit" value="提交">#}
{#    不行--會觸發form表單的提交 #}
{#    <button>提交</button>#}
{#    可以#}
{#    <input type="button">#}
</form>
{#可以#}
<button id="btn">提交</button><span id="error"></span>
</body>

<script>
    $("#btn").click(function () {
        $.ajax(
            {
               url:'/login/',
                type:'post',
                data:{'name':$("#name").val(),'pwd':$("#pwd").val()},
                dataType:'json',
                success:function (data) {
                    console.log(data)
                    if(data.status==100){
                        //跳轉到百度
                        location.href='https://www.baidu.com'
                    }else{
                        $("#error").html(data.msg).css({'color':'red'})
                        //設定一個定時器,3秒之後,清空span中的文字,第一個引數是匿名函式,第二個引數是時間
                        setTimeout(function () {
                            $("#error").html("")
                            //alert(1)
                        },1000)
                    }
                }
            }
        )
    })


</script>

前臺注意點:

-前臺:
        -取到id為error的元素,把data.msg的內容,放到裡面,然後給它設定樣式,顏色是紅色
        -$("#error").html(data.msg).css({'color':'red','margin-left':'10px'})
        -定時器:
            就是一個函式,傳了兩個引數,一個匿名函式,一個時間,
            在匿名函式中寫要處理的邏輯:
            -清空span標籤中的內容
            -$("#error").html("")

後臺views中:

def index(request):
    if request.method=="GET":
        return render(request,'index.html')



def login(request):
    #用字典做一個狀態,
    dic={'status':100,'msg':None}
    #後臺從前臺取資料,用POST方法通過key來取。
    name=request.POST.get('name')
    pwd=request.POST.get('pwd')
    #從資料庫查出使用者名稱和密碼一樣的物件
    user=models.User.objects.all().filter(name=name,pwd=pwd).first()
    if user:
        dic['msg']='登入成功'
    else:
        dic['status']=101
        dic['msg']='使用者名稱或者密碼錯誤'
    return JsonResponse(dic)

後臺注意點:

-後臺:
        -前臺如果是urlencoded編碼,直接從POST中取出資料
        -前臺如果是json編碼,從body中取出,處理
        -返回用:JsonResponse(dic),也可以用HttpRespone,(前端相應處理,在前臺寫dataType:'json')