In Django, when using jquery ajax post data, a 403 error will occur. Do you know how to solve it? Let me share two solutions with you below. Friends who need it can refer to it
In django, when using jquery ajax post data, a 403 error will occur
Method 1:
If jQuery is used to process ajax, Django I directly sent a piece of code to solve the problem. Put it in a separate js file and introduce it in the html page. Note that this js file must be introduced after the jquery js file is introduced
$(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 2:
Add @csrf_exempt decoration before the view that processes post data Symbols
For example
@csrf_exempt def profile_delte(request): del_file=request.POST.get("delete_file",'')
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
Detailed explanation of ajax jtemplate to implement dynamic paging
A simple implementation of Ajax showing progress during the request process
JQuery Ajax dynamically generates Table
The above is the detailed content of Solution to 403 error when using jquery ajax post data in django. For more information, please follow other related articles on the PHP Chinese website!