我想将数据发送到我的Django视图,同时重定向页面。所以,我认为ajax不在窗口。我不确定如何通过Jquery做到这一点。
答案 0 :(得分:3)
你不需要jQuery。 Create a form that performs a POST to the appropriate URL并提交。
答案 1 :(得分:0)
这是我通过POST将数据发送到Django服务器的代码。我访问了Ignacio建议的网站,并添加了csrf,因此它可以与典型的Django视图一起使用。
// 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();
}