0
我想将数据发送到我的Django视图并同时重定向页面。所以,我认为ajax不在窗口中。我不确定如何通过Jquery来做到这一点。发送javascript数据到Django视图
我想将数据发送到我的Django视图并同时重定向页面。所以,我认为ajax不在窗口中。我不确定如何通过Jquery来做到这一点。发送javascript数据到Django视图
你不需要这个jQuery。 Create a form that performs a POST to the appropriate URL并提交。
这是我通过POST发送数据到Django服务器的代码。我浏览了Ignacio建议的站点,并添加了csrf,以便与典型的Djano视图配合使用。
// get cookie using jQuery
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;
}
function post_to_url(path, params, method) {
method = method || "post"; // Set method to post by default if not specified.
// The rest of this code assumes you are not using a library.
// It can be made less wordy if you use one.
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);
}
}
csrfField = document.createElement("input");
var csrftoken = getCookie('csrftoken')
console.log("token" + csrftoken)
csrfField.setAttribute("type", "hidden");
csrfField.setAttribute("name", "csrfmiddlewaretoken");
csrfField.setAttribute("value", csrftoken)
form.appendChild(csrfField)
document.body.appendChild(form);
form.submit();
}
好的,谢谢!我得到一个CSRF验证失败403错误。我已经添加了JavaScript片段。 [链接](https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax) – Zach 2012-03-25 21:26:46
您需要通过'{%csrf_token%}'将CSRF令牌传递给JavaScript或使用[CSRF装饰器]之一(https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#utilities)来修改视图上的CSRF处理。 – 2012-03-25 21:28:58
好的再次感谢 – Zach 2012-03-25 21:37:52