1 什么是ajax:
异步的JavaScript和xml,跟后台交互,都用json
2 ajax干啥用的?
前后端做数据交互:
3 特点:
-异步(异步和同步的区别:同步是请求发过去,要等着回应;异步:不需要等回应,可以进行其他操作)
-局部刷新:
4 使用ajax实现一个简单的文件上传页面
前端页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="/static/jquery-3.3.1.js"></script>
<title>Title</title>
</head>
<body>
<form action="/files/" method="post" enctype="multipart/form-data">
<p>用户名:<input type="text" name="name" id="name"></p>
<p><input type="file" name="myfile" id="myfile"></p>
<input type="submit" value="提交">
</form>
<button id="btn">ajax提交文件</button>
</body>
<script>
$("#btn").click(function () {
//上传文件,必须用FormData
var formdata=new FormData();
formdata.append(\'name\',$("#name").val());
//取出文件$("#myfile")[0].files拿到的是文件列表,取第0个把具体的文件取出来
formdata.append(\'myfile\',$("#myfile")[0].files[0]);
$.ajax({
url:\'/files_ajax/\',
type:\'post\',
//不预处理数据,(name=lqz&age=18)
processData:false,
//指定往后台传数据的编码格式(urlencoded,formdata,json)
//现在用formdata对象处理了,就不需要指定编码格式了,不要给我编码了
contentType:false,
data:formdata,
success:function (data) {
alert(data)
}
})
})
</script>
</html>
后台views.py中的页面
def files_ajax(request):
# 提交文件从,request.FILES中取,提交的数据,从request.POST中取
name=request.POST.get(\'name\')
print(name)
dic_files = request.FILES
myfile = dic_files.get(\'myfile\')
with open(myfile.name, \'wb\') as f:
# 循环上传过来的文件
for line in myfile:
# 往空文件中写
f.write(line)
return HttpResponse(\'ok\')
5 基于ajax提交json格式的数据(简单的用户登录认证)
前端页面
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>登录验证</title>
<script src="/static/jquery-3.3.1.js"></script>
</head>
<body>
<form>
<p>用户名:<input type="text" name="user" id="name"></p>
<p>密码:<input type="password" name="pwd" id="pwd"></p>
</form>
<button id="btn">提交</button>
<p class="test"></p>
</body>
<script>
$(\'#btn\').click(function () {
var dic = {\'name\':$(\'#name\').val(),\'pwd\':$(\'#pwd\').val()};
var msg = JSON.stringify(dic);
var $test = $(\'.test\');
$.ajax({
url:\'/login/\',
type:\'post\',
//指定请求的数据格式为json
contentType:\'application/json\',
data:msg,
//指定响应的格式为json,注意如果后台没有放回json类型的数据格式下方的success不会执行
dataType:\'json\',
success:function (res) {
data = JSON.parse(res);
if (data == \'2\'){
$test.text(\'登录失败!\')
} else if (data == \'1\'){
location.href=\'https://www.baidu.com/\'
}
}
});
});
</script>
</html>
后台views.py中的内容
from django.shortcuts import render, redirect, HttpResponse
import json
from loginapp.models import *
# Create your views here.
def login(request):
if request.method == \'GET\':
return render(request, \'login.html\')
if request.method == "POST":
msg = json.loads(request.body.decode(\'utf-8\'))
print(msg)
res = User.objects.filter(user=msg[\'name\'], pwd=msg[\'pwd\']).first()
if res:
return HttpResponse(json.dumps(\'1\'))
else:
return HttpResponse(json.dumps(\'2\'))