1.添加ajax登陸視圖函數
def login_ajax(request):
return render(request, 'booktest/login_ajax.html')
def login_ajax_check(request):
username = request.POST.get('username')
password = request.POST.get('password')
print(username+':'+password)
if username == 'admin' and password == '111':
return JsonResponse({'res': 1})
else:
return JsonResponse({'res': 0})
2.在app模板裏面增加login_ajax.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax登陸頁面</title>
<script src="/static/js/jquery-1.7.1.min.js"></script>
<script>
$(function(){
$('#btnAjaxLogin').click(function(){
username=$('#username').val();
password=$('#password').val();
$.ajax({
'url':'/login_ajax_check',
'type':'post',
'data':{'username':username,'password':password},
'dataType':'json',
}).success(function(data){
if(data.res==0){
$('#errmsg').show().html('用戶名或者密碼錯誤');
}else{
location.href='/index';
};
});
});
});
</script>
<style>
#errmsg{
display:none;
color:red;
}
</style>
</head>
<body>
用戶名:<input type="text" id="username"/><br/>
密碼:<input type="password" id="password"/><br/>
<input type="button" id="btnAjaxLogin" value="登陸">
<div id="errmsg"></div>
</body>
</html>
3.添加路由
url(r'^login_ajax$', views.login_ajax),
url(r'^login_ajax_check$', views.login_ajax_check),
4.測試