基于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')
原文地址:https://www.cnblogs.com/fxc-520520/p/9990774.html