Ajax的作用是在不重新加载页面的情况下实现页面的局部刷新。本例子采用的语言是python3,工具为pycharm,服务器为Django,前端使用query-3.2.1.min.js。
1.创建Django项目,创建static静态文件夹存放query-3.2.1.min.js。在setting.py中添加配置:
STATICFILES_DIRS = [os.path.join(BASE_DIR,'static')]
2.前端代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登陆</title>
<script src="/static/js/jquery-3.2.1.min.js"></script>
<script>
$(function () {
$('#commit').click(function () {
username = $('#username').val()
password = $('#password').val()
$.ajax({
url:'/login_check_ajax',
type:'post',
data:{'username':username,'password':password},
dataType:'json',
success:function (data) {
if (data.res == 0){
$('#message').show().html('用户名或密码不正确')
} else {
location.href='index'
}
}
})
})
})
</script>
<style>
#message{
display: none;
color: red;
}
</style>
</head>
<body>
<div>
<input type="text" id="username">
</div>
<div>
<input type="password" id="password" id="">
</div>
<div id="message"></div>
<div>
<input type="button" value="登陆" id="commit">
</div>
</body>
</html>
3.后台代码:
from django.shortcuts import render,redirect
from django.http.response import JsonResponse
#首页视图函数
def index(request):
return render(request,'index.html')
#Ajax登陆页面
def login_ajax(request):
return render(request,'login_ajax.html')
#Ajax请求视图函数
def login_check_ajax(request):
username = request.POST.get('username')
password = request.POST.get('password')
#如果用户名为fucker,密码为123456则返回1,否则但会0
if username == 'fucker' and password == '123456':
return JsonResponse({'res':1})
else:
return JsonResponse({'res':0})
4.设置urls.py
urlpatterns = [
path('index',views.index),
path('login_ajax',views.login_ajax),
path('login_check_ajax',views.login_check_ajax),
]
5.启动Django服务,打开浏览器,访问http://127.0.0.1:8000/login_ajax
用户名密码输入正确时,直接跳转首页,错误时给出错误提示