Home>

In django, using jquery ajax post data, I get a 403 error

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=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;
  }
  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 (0, origin.length + 1) == origin + "/") ||
      (url == sr_origin || url.slice (0, sr_origin.length + 1) == 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 Black hat seo hijacker, js hijack search engine code
  • Next JQuery to achieve picture carousel effect