[英]Django CSRF check failing in JavaScript post request like a form submit
我在这里使用答案( JavaScript提交请求,例如表单提交 )在浏览器中以我的JavaScript进行发布。 但是Django CSRF检查失败,因为模板中的表单中包含{%csrf_token%}。 怎么做?我应该添加以下代码吗?
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", 'csrfmiddlewaretoken');
hiddenField.setAttribute("value", '{{ csrf_token }}');
form.appendChild(hiddenField);
欢迎任何提示,建议和意见。 谢谢
如果要使用ajax提交表单,则还必须提交csrf令牌值。 举个例子。
$.ajax({
type: "POST",
url: url,
data:{
'csrfmiddlewaretoken':$('input[name="csrfmiddlewaretoken"]').val(),
},
success: function(response){
}
});
或者您可以将ajax数据中的序列化表格发送为
data: $("#form").serialize(),
我使用了https://github.com/sigurdga/django-jquery-file-upload/blob/master/fileupload/static/js/csrf.js中的getCookie()函数和JavaScript发布请求中的 post()函数表格提交 。
最终代码:
// https://github.com/sigurdga/django-jquery-file-upload/blob/master/fileupload/static/js/csrf.js
function getCookie(name) {
console.log('getCookie');
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;
}
}
}
console.log('cookie:' + cookieValue);
return cookieValue;
}
// https://stackoverflow.com/questions/133925/javascript-post-request-like-a-form-submit
function post(path, params, method) {
method = method || "post"; // Set method to post by default if not specified.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
for(var key in params) {
if(params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
var hiddenField1 = document.createElement("input");
hiddenField1.setAttribute("type", "hidden");
hiddenField1.setAttribute("name", 'csrfmiddlewaretoken');
hiddenField1.setAttribute("value", getCookie('csrftoken'));
form.appendChild(hiddenField1);
document.body.appendChild(form);
form.submit();
}
欢迎任何意见。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.