django-Ajax发送POST请求(csrf跨站请求的三种方式)
方法1:要在ajax发送请求前加上
$.ajaxSetup({
data:{csrfmiddlewaretoken:'{{ csrf_token }}'},
});
注意:{{ csrf_token }} ,是需要渲染的,不能脱离模板,所以是外部文件引入的话,不能执行,
{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="{% static 'jquery-3.2.1.js' %}"></script>
</head>
<body>
<button>ajax发送</button>
</body>
<script>
$("button").click(function () {
$.ajaxSetup({
data:{csrfmiddlewaretoken:'{{ csrf_token }}'},---------
});
$.ajax({
url:"/ajax_send/",
data:{"user":"gu"},
type:"POST",
success:function (data) {
alert(data)
}
})
})
</script>
</html>
方法2:在ajax发送请求是加上csrfmiddlewaretoken,的值,
$.ajax({
url:"/ajax_send/",
data:{"user":"gu","csrfmiddlewaretoken":$("[name='csrfmiddlewaretoken']").val()},-----与方法1的功能一样,
但这种方法可以作为一个外部文件引入,
type:"POST",
success:function (data) {
alert(data)
}
})
})
-------

方法3:修改header,
在views打印cookie可以得到csrftoken
def index(request):
print("cookie",request.COOKIES)
#cookie {
# 'csrftoken': 'AB9v1MGTbdpSGg3FaGCIiUxrKVR8zKSqgdGFDn5E0ADsJ2ST7N2zgW6KboQ8G31x',
# 'sessionid': 'eexw5p38vky9qo38nf372dz5lj1br6xf'
# }
#cookie 是浏览器给的,
return HttpResponse("index")
需要先下载一个jquery.cookie.js插件文件,然后引用,
<script src="{% static 'jquery.cookie.js' %}"></script>
{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
{# <script src="{% static 'jquery-3.2.1.js' %}"></script>#}
<script src="{% static 'jquery.cookie.js' %}"></script>
</head>
<body>
{#<form action="/login/" method="post">#}
{# csrf_token 在前端会渲染出一个input标签,是一组键值对,键是csrfmiddlewaretoken,值是随机字符串,会随着下面的input标签一起提交,只有这种形式发送post的请求才能被接收,#}
{##}
{# {% csrf_token %}#}
{# <p>用户名:{{ form_obj.user }}</p>#}
{# <p>密 码:{{ form_obj.pwd }}</p>#}
{# <input type="submit">#}
{##}
{#</form>#}
<button>ajax发送</button>
</body>
<script>
{# $("button").click(function () {#}
{##}
{# $.ajaxSetup({#}
{# data:{csrfmiddlewaretoken:'{{ csrf_token }}'},#}
{# });#}
{##}
{# $.ajax({#}
{##}
{# url:"/ajax_send/",#}
{# data:{"user":"gu","csrfmiddlewaretoken":$("[name='csrfmiddlewaretoken']").val()},#}
{# type:"POST",#}
{# success:function (data) {#}
{# alert(data)#}
{# }#}
{##}
{#{)#}
$('button').click(function () {
$.ajax({
url:"/ajax_send/",
type:"post",
headers:{"X_CSRFToken":$.cookie('csrftoken')},---------------
success:function () {
alert(123)
}
})
})
</script>
</html>
-----
input 标签的上传文件,
在前端页面
{#发送文件的时候,要加上enctype ,是以块的方式发送文件,#}
<form action="/login/" method="post" enctype="multipart/form-data">
<input type="file" name="fileobj">
</form>
<button>ajax发送</button>
在views文件中,获取文件,保存文件,
def login(request):
if request.method == "POST":
print("post",request.POST.get("fileobj"))
print("post",type(request.POST.get("fileobj")))
print("===",request.FILES)
fileobj = request.FILES.get("fileobj")
#创建一个文件句柄,把文件存起来,
f=open(fileobj.name,'wb')
for i in fileobj.chunks():#按块存
f.write(i)

浙公网安备 33010602011771号