Home>

This article introduces to you through two methods. In Django, using jquery ajax post data, a 403 error will occur. For details, see the following.

method one:

If you use jQuery to handle Ajax, Django directly sends a piece of code to solve the problem.Put it in a separate js file and import it in the html page.Note that this js file must be imported after the js file of jquery,Re-introduction

$(document) .ajaxsend (function (event, xhr, settings) {
 function getcookie (name) {
  var cookievalue=null;
  if (document.cookie&&document.cookie!="") {
   var cookies=document.cookie.split (";");
   for (var i =;i<cookies.length;i ++) {
    var cookie=jquery.trim (cookies [i]);
    //does this cookie string begin with the name we want?
    if (cookie.substring (, name.length +) == (name + "=")) {
     cookievalue=decodeuricomponent (cookie.substring (name.length +));
     break;
    }
   }
  }
  return cookievalue;
 }
 function sameorigin (url) {
  //url could be relative or scheme relative or absolute
  var host=document.location.host;//host + port
  var protocol=document.location.protocol;
  var sr_origin="//" + host;
  var origin=protocol + sr_origin;
  //allow absolute or scheme relative urls to same origin
  return (url == origin || url.slice (, origin.length +) == origin + "/") ||
   (url == sr_origin || url.slice (, sr_origin.length +) == sr_origin + "/") ||
   //or any other url that isn "t scheme relative or absolute i.e relative.
   ! (/^ (\/\/| http:| https:). * /. test (url));
 }
 function safemethod (method) {
  return (/^(get|head|options|trace)$/.test(method));
 }
 if (! safemethod (settings.type)&&sameorigin (settings.url)) {
  xhr.setrequestheader ("x-csrftoken", getcookie ("csrftoken"));
 }
});

Method Two:

Add the @csrf_exempt decorator to the view that processes post data

E.g

@csrf_exempt
def profile_delte (request):
 del_file=request.post.get ("delete_file", "")
  • Previous How to fix jQuery EasyUI Dialog
  • Next Ajax upload video with progress bar asynchronously and extract thumbnails