Ajax request not working properly in django

后端 未结 2 1361
臣服心动
臣服心动 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!

提交回复
热议问题