15 Ajax技术
一、简介
特点
- 异步请求
- 局部刷新
二、Ajax的实现
jQuery实现Ajax
- url:请求的URL
- type:请求方式
- data:请求发送的数据,type为get数据会拼接到url中
- success:请求成功后执行的回调函数
Form实现文件上传
- form表单的enctype类型设置成multipart/form-data数据类型
Django获取上传的文件对象:
file=request.FILES
def fileput(request): if request.method=="GET": return render(request,'fileput.html') else: data=request.POST file=request.FILES file_obj=file.get('avatar') file_name=file_obj.name with open(file_name,'wb') as f: for line in file_obj: f.write(line) return HttpResponse('ok')
contentType头类型
form表单:
- application/x-www-form-urlencoded:默认,只能上传字符串
- multipart/form-data:上传文件
ajax:
- application/x-www-form-urlencoded:默认值,只能上传字符串
- application/json :发送json数据
Ajax发送json数据
前端ajax
$("input[type=button]").click(function () {
$.ajax({
url:'login/',
type:'post',
contentType:'application/json',
data:JSON.stringify({
a:1,
b:2
}),
success:function (data) {
console.log(data)
}
})
});
Django后端
request.POST只有当contentType=urlencoed时才有数据
request.body 请求报文中的请求体
def login(request): print(request.body) print(request.POST)

前端用urlencoded编码时,django的request.body一样还是有数据
$("input[type=button]").click(function () {
$.ajax({
url:'login/',
type:'post',
//contentType:'application/json',
data:{
a:1,
b:2
},
success:function (data) {
console.log(data)
}
})
});

也就是只有contentType为urlencoed时,才会将request.body内容解析成字典request.POST
Ajax文件上传
ajax前端
//ajax文件上传 $("input[type=button]").click(function () { var formdata=new FormData();//固定格式创建formData formdata.append("user",$("#user").val());//append方法添加键值对 file=$("#avatar")[0].files[0];//获取文件对象 formdata.append("avatar",file);//添加文件键值对 $.ajax({ url:'fileput/', type:'post', contentType:false,//对数据不做预处理,不做任何编码,编码交由FormData处理 processData:false, data:formdata, success:function (data) { console.log(data) } }) })
django后端和form表单一样,获取request.FILES对象

浙公网安备 33010602011771号