In Django, using jquery Ajax post data, there is a 403 error
Method One:
If you use jquery to handle Ajax, Django sends a problem-solving code directly. Put it in a separate JS file, in the HTML page can be introduced. Note that this JS file must be in the jquery JS file introduced after the introduction can be
$ (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 (n
Ame.length + 1));
Break
}} return cookievalue; function Sameorigin (URL) {//URL could be relative or scheme relative or absolute var host = Document.loca Tion.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 of the other URLs 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", GetCoo
Kie (' Csrftoken ')); }
});
Method Two:
Add @csrf_exempt to the view before processing post data
For example
@csrf_exempt
def profile_delte (request):
del_file=request. Post.get ("Delete_file", "")
The above two methods to solve the Django Ajax post 403 error, of course, the solution is more than these two, welcome to share their views, this article is not good, please forgive me, thank you.