简体   繁体   中英

AJAX Post request from Javascript to Python (Django, views.py)

I am trying to send a POST request from javascript to views.py using AJAX. However, I am getting a 403 Error stating that csrf token is not present.

In order to resolve this issue I followed this link and included the function in my javascript. However, I am confused as to what the next step should be.

Any assistance will be appreciated. Thanks!

Simply add somewhere in your template:

{% csrf_token %}

Then in your js file should be smth like this:

var csrf_token;

var sendSomeAjax = function(target) {
    var requestUrl = $(target).data('url');

    return $.ajax({
        url: requestUrl,
        type: 'post',
        headers: {
            'X-CSRFToken': csrf_token
        },
        dataType: 'json'
        // also you can pass some 'data: ' here
    })
};

$(function() {
    csrf_token = $('input[name="csrfmiddlewaretoken"]').val();

    var target = $('.someSelectorWhereYouHavePassedDataUrlToYourView');
    // for example in your template <a href="#" data-url="{% url 'app_url_namespace:view_url_name' %}"</a>

    sendSomeAjax(target).success(function(data) {
        // do smth with data =)
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM