異步的javascript
在不全部加載某一個(gè)頁面部的情況下 對頁面進(jìn)行局的刷新
ajax請求都在后臺
登錄案例
訪問登錄頁面 頁面顯示登錄窗口
頁面內(nèi)嵌ajax將輸入在頁面的信息傳遞給檢測視圖
視圖收到的不管是html傳遞的還是ajax傳遞的都使用request.POST或GET接收
檢測視圖檢查輸入是否正確返回對應(yīng)的json給ajax
檢測視圖只返回json而不重定向 如果重定向 將只在ajax后臺顯示
當(dāng)輸入正確 ajax 重定向到成功登錄后的頁面
當(dāng)輸入錯(cuò)誤 ajax 提示錯(cuò)誤信息而不刷新頁面
ajax是異步執(zhí)行的 JS在執(zhí)行到ajax時(shí)并不會(huì)等待ajax的阻塞
HTML內(nèi)容:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax登陸頁面</title>
<script src="/static/js/jquery-1.12.4.min.js"></script>
<script>
$(function(){
//綁定btnAjax 的click 事件
$("#btnAjax").click(function(){
login_name=$("#username").val()
login_passwd=$("#userpasswd").val()
$.ajax({
"url":"ajax_handle",
"type":"post",
"data":{
"name":login_name,
"passwd":login_passwd
},
"dataType":"json"
}).success(function(data){
//進(jìn)行處理
if (data.res == 0){
$("#errmsg").show().html("用戶名或密碼錯(cuò)誤")
}
else{
location.href = "/"
}
})
})
})
</script>
<style>
#errmsg{
display: none;
color: red;
}
</style>
</head>
<div>
<label>登陸<input type="text" id="username"></label><br />
<label>密碼<input type="password" id="userpasswd"></label><br />
<input type="button" id="btnAjax" value="登陸">
<div id ="errmsg"></div>
</div>
</html>
視圖函數(shù)內(nèi)容:
def ajax_login(request):
return render(request, "book/test_ajax.html")
def ajax_handle(request):
u_name = request.POST.get("name")
u_password = request.POST.get("passwd")
try:
if Login.objects.get(name=u_name) and Login.objects.get(password=u_password):
return JsonResponse({"res": 1})
except Login.DoesNotExist:
return JsonResponse({"res": 0})