輸入賬號密碼,進行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反序列化爲數組類型。