问题
I have 2 $.ajax()
functions in one html rendered by Django. The first one works correctly, the second one answers with a 403 CSRF Failed: CSRF token missing or incorrect.
This is the relevant js code:
$(document).ready(function(){
window.CSRF_TOKEN = "{{ csrf_token }}";
....
$.ajax({
method: "POST",
url: "{% url 'alpha:create_cart_item' %}",
data: {'item': stockitem_id, 'quantity': '1', 'csrfmiddlewaretoken': window.CSRF_TOKEN},
success: function(resp){...}
....
$.ajax({
method: "PUT",
url: "{% url 'alpha:update_cart_item' 0 %}".replace("0", cartitem_id),
data: {'pk': cartitem_id, 'csrfmiddlewaretoken': window.CSRF_TOKEN},
success: function(resp){
panel_div.hide();
},
error: function(resp){
}
});
The second Ajax request is not working. I set the csrfmiddlewaretoken in the exact same way. Why am I getting the 403?. Obviously I'm missing something, please help.
UPDATE
Debugging this I found out that if I change the method o the 2nd request to "POST", it works correctly. But I do need the method to be "PUT".
Also, I'm using Django REST Framework...
来源:https://stackoverflow.com/questions/39520340/two-ajax-requests-2-csrf-tokens-one-for-post-one-for-put-not-working-403-erro