在django中,使用jquery ajax post数据,会出现403的错误

来源:互联网 发布:施工预算软件下载 编辑:程序博客网 时间:2024/06/18 00:36

在django中,使用jquery ajax post数据,会出现403的错误


方法一:


如果用jQuery来处理ajax的话,Django直接送了一段解决问题的代码。把它放在一个独立的js文件中,在html页面中都引入即可。注意这个js文件必须在jquery的js文件引入之后,再引入即可

[javascript] view plaincopyprint?
  1. $(document).ajaxSend(function(event, xhr, settings) {  
  2.     function getCookie(name) {  
  3.         var cookieValue = null;  
  4.         if (document.cookie && document.cookie != '') {  
  5.             var cookies = document.cookie.split(';');  
  6.             for (var i = 0; i < cookies.length; i++) {  
  7.                 var cookie = jQuery.trim(cookies[i]);  
  8.                 // Does this cookie string begin with the name we want?  
  9.                 if (cookie.substring(0, name.length + 1) == (name + '=')) {  
  10.                     cookieValue = decodeURIComponent(cookie.substring(name.length + 1));  
  11.                     break;  
  12.                 }  
  13.             }  
  14.         }  
  15.         return cookieValue;  
  16.     }  
  17.     function sameOrigin(url) {  
  18.         // url could be relative or scheme relative or absolute  
  19.         var host = document.location.host; // host + port  
  20.         var protocol = document.location.protocol;  
  21.         var sr_origin = '//' + host;  
  22.         var origin = protocol + sr_origin;  
  23.         // Allow absolute or scheme relative URLs to same origin  
  24.         return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||  
  25.             (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||  
  26.             // or any other URL that isn't scheme relative or absolute i.e relative.  
  27.             !(/^(\/\/|http:|https:).*/.test(url));  
  28.     }  
  29.     function safeMethod(method) {  
  30.         return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));  
  31.     }  
  32.   
  33.     if (!safeMethod(settings.type) && sameOrigin(settings.url)) {  
  34.         xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));  
  35.     }  
  36. });  


方法二:

在处理post数据的view前加@csrf_exempt装饰符

例如

[python] view plaincopyprint?
  1. @csrf_exempt  
  2. def profile_delte(request):  
  3.     del_file=request.POST.get("delete_file",'')  
  4.       
原创粉丝点击