简体   繁体   中英

django error ajax CSRF token missing or incorrect without jquery

django csrf_token error 403 with js

    var httpRequest = new XMLHttpRequest();

    var links = document.querySelectorAll('form')

    for (var i = 0; i <  links.length; i++) {
        var link = links[i]
        link.addEventListener('submit', function(e) {
            e.preventDefault()

            httpRequest.onreadystatechange = function() {
                if (httpRequest.readyState === 4) {
                    document.getElementById('result').innerHTML = httpRequest.responseText
                }
            }

            httpRequest.open('POST', this.getAttribute('action'), true)
            httpRequest.send()

        })
    }

You should be able to set headers on XMLHttpRequest by doing:

var token = '{{csrf_token}}';

var httpRequest = new XMLHttpRequest();
httpRequest.setRequestHeader("X-CSRFToken", token);

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