基于w3schools ajax example我正在尝试进行删除调用,然后从表中删除相应的行。这里有很多关于如何使用 JQuery 的答案,但我不会这样做。我发现this answer这让我像这样编写 JavaScript:
function deleteFullLicense(rowid, objectid) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 204) {
row = document.getElementById(rowid);
row.parentNode.removeChild(row);
}
else {
window.alert("Something went wrong. The delete failed.");
}
};
xhttp.open("POST", "deleteLicense/" + objectid, true);
xhttp.send({'csrfmiddlewaretoken': '{{ csrf_token }}'});
}
但我收到 Forbidden(CSRF token 丢失或不正确。)
消息。我应该如何发送 token ?
最佳答案
事实证明,如果我将其命名为X-CSRFToken
,它就会起作用。发现了here if you want to read more .
function deleteFullLicense(rowid, objectid) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 204) {
row = document.getElementById(rowid);
row.parentNode.removeChild(row);
}
};
xhttp.open("POST", "deleteLicense/" + objectid, true);
xhttp.setRequestHeader("X-CSRFToken", '{{ csrf_token }}')
xhttp.send();
}
关于javascript - 如何在 AJAX 中传递 Django csrf token (不使用 jQuery),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36844101/