2016-04-25 66 views
0

基於w3schools ajax example我試圖進行刪除調用,然後從表中刪除相應的行。這裏有很多關於如何使用JQuery來做的答案,但我沒有這樣做。我發現this answer這讓我寫我的JavaScript是這樣的:如何在AJAX中傳遞Django csrf標記(不含jQuery)

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 missing or incorrect.)。我應該如何發送令牌?

+1

您需要設置爲標題。 也許這可以幫助你:http://stackoverflow.com/questions/22063612/adding-csrftoken-to-ajax-request – rubentd

+0

我試圖將它設置爲標題使用:'xhttp.setRequestHeader(「csrfmiddlewaretoken」,'{ {csrf_token}}')'但沒有區別。還有什麼需要做的嗎? – jonalv

回答

0

原來,如果我把它叫做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(); 
}