前端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')