
<script src="http://code.jquery.com/jquery-latest.js"></script>#引入jQuery
#當點擊函數為test()的按鈕時觸發ajax請求,url為請求路徑,dataType為數據類型,type默認為get可以不寫
<script>
function test() {
$.ajax({
'url': '/ajax_handle',
'dataType': 'json',
'async':false,#默認是異步的(true是異步的)
}).success(function (data) {
alert(data.res)
})
}
</script>
#在urls里設置
url('^ajax_handle$', views.ajax_handle),
#在views視圖里設置
def ajax_handle(request):
return JsonResponse({'res': 111})
用ajax登錄用戶名密碼方案
#以下為前端html中的代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
<style>
#message {
display: none;
color: red;
}
</style>
</head>
<body>
<form action="/login/" method="post">
<input type="text" id="username" >
<input type="password" id="password">
<input type="button" value="登錄" onclick="login()">
</form>
<div id="message"></div>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function login() {
username = $('#username').val()
password = $('#password').val()
$.ajax({
'url': '/login/',
'type': 'post',
'dataType': 'json',
'data':{'username': username, 'password': password}
}).success(function (data) {
if (data.res == 0){
$('#message').show().html('用戶名密碼錯誤!!!')
}
else {
location.href = '/index' #跳轉/index頁面
}
})
}
</script>
</body>
</html>
#后端views里代碼
def login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
if username == 'root' and password == 'lizhaoqwe':
return JsonResponse({'res': 1})#1表示登錄成功
else:
return JsonResponse({'res': 0})#0表示登錄失敗
return render(request, 'login.html')