发送请求的方式:
1.form表单 post/get
(1) action 提交的地址 method 提交的方式
(2)input标签要有name属性
(3)要有type=submit 或 button按钮
2.地址栏直接输入URL get
3.a标签 get
ajax
1.与服务器进行交互,是js技术,发送请求,传输数据是XML(json)
2.特点: 异步,局部刷新,数据量少
异步交互:客户端发送一个请求,无需等待服务器的响应结束,就可以发送第二个请求
3.使用:
用Jquery发ajax
先导入Jquery
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
写js代码
$.ajax({
url: '/ajax_test/', # 提交的地址
type: 'post', # 提交的方式
data: { # 数据
name: 'xiaobai',
age: 73,
hobby: JSON.stringify(['吃', 'cnb', '画大饼'])
},
success: function (res) { # 回调函数
$('[name="ii3"]').val(res)
},
error: function (res) {
console.log(res)
}
})
json: 一种数据类型
python
数据类型: 数字 字符串 布尔值 列表 字典 None
序列化:python的数据类型 ——》 json字符串
json.dumps(python的数据类型)
json.dump(python的数据类型, f )
反序列化: json字符串 ——》 python的数据类型
json.loads( json字符串 )
json.load( json字符串, f)
前端
数据类型: 数字 字符串 布尔值 数组 对象 null
序列化: JSON.stringify(数据类型) ——》 json字符串
反序列化: JSON.parse(json字符串) ——》前端的数据类型
JsonResponse
from django.http import JsonResponse
return JsonResponse({'xxx':'xxxx'}) # content_type: application/json'
JsonResponse([],safe=False)
4.ajax上传文件
<script>
$('#b1').click(function () {
var form_obj = new FormData(); # 组建FormData对象
form_obj.append('x1', $('#f1')[0].files[0]);
$.ajax({
url: '/upload/',
type: 'post',
data: form_obj,
processData:false, # 不处理编码方式
contentType:false, # 不处理 contentType请求头
success: function (res) {
alert('OK')
}
})
})
</script>
注意:processData:false时,编码方式是:enctype="multipart/form-data" 当processData:true时,编码方式是:enctype="application/x-www-form-urlencoded"
view中:
def upload(request):
if request.is_ajax(): # 判断是否是ajax请求
# 拿到文件
file_obj = request.FILES.get('x1')
# 接收文件
with open(file_obj.name,'wb')as f:
for i in file_obj.chunks():
f.write(i)
return HttpResponse('ok')
return render(request,'upload.html')
5.ajax通过django的CSRF校验:
前提条件:保证访问的页面有csrftoken的cookie
(1)模板中使用csrf_token标签
(2)给视图加装饰器
from django.views.decorators.csrf import ensure_csrf_cookie # 确保访问某个视图有csrf_cookie
方式一:
$.ajax({
url: '/calc/',
type: 'post',
data: {
csrfmiddlewaretoken:$('[name="csrfmiddlewaretoken"]').val() ,
i1: $('[name="i1"]').val(),
i2: $('[name="i2"]').val(),
},
success: function (res) {
$('[name="i3"]').val(res)
}
})
方式二:
$('#b2').click(function () {
$.ajax({
url: '/calc2/',
type: 'post',
headers:{
'X-csrftoken': $('[name="csrfmiddlewaretoken"]').val(),
},
data: {
i1: $('[name="ii1"]').val(),
i2: $('[name="ii2"]').val(),
},
success: function (res) {
$('[name="ii3"]').val(res)
}
})
});