Ajax request not working properly in django

后端 未结 2 1362
臣服心动
臣服心动 2021-01-27 10:09

JS code for ajax request



        
相关标签:
2条回答
  • 2021-01-27 10:15

    This is because you need to set up CSRF in your AJAX request, same as you'd do in normal request.

    Add the following code to your JavaScript:

    // This handles generation of CSRF token
    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;
    }
    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
                xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
            }
        }
    });
    

    refer to docs: https://docs.djangoproject.com/en/2.0/ref/csrf/#ajax

    I hope this helps.

    Good luck!

    0 讨论(0)
  • 2021-01-27 10:30

    It is normal, it's beacause of the CSRF token. Try this:

    var csrftoken = $('[name="csrfmiddlewaretoken"]').val();
    

    And after include this in your Ajax request

    $.ajax({
     ...
     headers: {
        'Accept': 'application/json', //if json
        'Content-Type': 'application/json', //if json
        "X-CSRFToken": csrftoken
        },
        credentials: 'include',
     ....
    })
    

    It worked for me

    0 讨论(0)
提交回复
热议问题