Django ajax
什么是ajax?
AJAX(Asynchronius Javascript And XML) 异步的Javascript和XML,使用js语言和服务器进行,传输数据为XML(也可以是其它类型)
ajax 发送请求 局部刷新 异步
js里面把对象转换成 json JSON.stringify() 反序列化 JSON.parse()
通过ajax实现数据请求小案例:
加法小案例 view代码 def index(request): print(request.method) if request.method == 'POST': i1 = request.POST.get('a1') i2 = request.POST.get('a2') i3 = int(i1)+ int(i2) # return render(request,'index.html',{"i1":i1,"i2":i2,"i3":i3}) return HttpResponse(i3) return render(request,'index.html') 模板文件代码 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <input type="text" name="i1"> + <input type="text" name="i2"> =<input type="text" name="i3"> <button id="b1">计算</button> {% load static %} <script src="{% static 'jQuery/js/jquery.js' %}"></script> <script> $('#b1').click(function () { $.ajax({ url:'/index/', type:'post', data:{ a1:$('input[name="i1"]').val(), a2:$('input[name="i2"]').val(), }, success:function (ret) { $('input[name="i3"]').val(ret) } }) }) </script> </body> </html>
ajax参数
获取数据实例
前端模板 文件传列表后端获取 后端view代码 def test(request): name = request.POST.get('name') age = request.POST.get('age') hobby = request.POST.getlist('hobby[]',) print(request.POST) print(name) print(age) print(hobby) return HttpResponse("ok") 前端模板文件内容 $('#b2').click(function () { $.ajax({ url:'/test/', type:'post', data:{ name:'ivy', age:'18', hobby:["reading","writing","singing"] }, success:function (ret) { alert(111) } }) })
实例二
通过传参方式改变后端取值方法 view里代码 import json def test(request): name = request.POST.get('name') age = request.POST.get('age') hobby = json.loads(request.POST.get('hobby')) print(request.POST) print(name) print(age) print(hobby) return HttpResponse("ok") 前端代码 $('#b2').click(function () { $.ajax({ url:'/test/', type:'post', data:{ name:'ivy', age:'18', hobby:JSON.stringify(["reading","writing","singing"]) }, success:function (ret) { alert(111) }, error:function (ret) { alert(ret) } }) })
上传文件实例
view里面的代码 from django.http.response import JsonResponse def upload(request): file_obj = request.FILES.get("f1") with open(file_obj.name,'wb') as f: for i in file_obj: f.write(i) return JsonResponse({'status':200,'msg':"successful"}) 前端代码 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <input type="file" id="f1"> <button id="b3">上传文件</button> {% load static %} <script src="{% static 'jQuery/js/jquery.js' %}"></script> <script> $('#b3').click(function () { var form_data = new FormData(); form_data.append("f1",$('#f1')[0].files[0]); //获取文件对象 $.ajax({ url:'/upload/', type:'post', processData:false, //告诉jquery不要处理发送的数据 contentType:false, //告诉jQuery不去设置Content_Type data:form_data, success:function (ret) { console.log(ret) }, error:function (ret) { alert(ret) } }) }) </script> </body> </html>
Ajax通过django的csrf校验
提交post请求的设置 1.在data中添加csrfmiddlewaretoken 键值对 $('#b1').click(function () { $.ajax({ url:'/index/', type:'post', data:{ csrfmiddlewaretoken:$('input[name="csrfmiddlewaretoken"]').val(), a1:$('input[name="i1"]').val(), a2:$('input[name="i2"]').val(), }, success:function (ret) { $('input[name="i3"]').val(ret) } }) }) 2.方法2 $('#b1').click(function () { $.ajax({ url:'/index/', type:'post', headers:{ 'x-csrftoken':$('input[name="csrfmiddlewaretoken"]').val(), }, data:{ a1:$('input[name="i1"]').val(), a2:$('input[name="i2"]').val(), }, success:function (ret) { $('input[name="i3"]').val(ret) } }) })
因为中间件里面就是拿这两个值来做比较的。
引入js文件自动设置全局
js文件代码如下 function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function (xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } });
加装饰器做csrf中间件校验
from django.views.decorators.csrf import csrf_exempt,csrf_protect,ensure_csrf_cookie
csrf_exempt:表示不需要进行csrf校验
csrf_protect:表示某一个视图需要csrf校验 当把全局的注释以后
ensure_csrf_cookie: 确保视图返回的时候带上对应的cookie,不用在模板里面写{% csrf_token%}
We are down, but not beaten. tested but not defeated.