我从django后端获取ajax发布数据时遇到问题,我不知道如何传递该值,请帮忙。
在HTML中我只是这个:
<form id="get_vulns_from_family">
<label for="family_content">Enter a family name to display the NVTs</label>
<input id="family_content" />
<input type="submit" value="search" />
</form>
在javascript中我写了这个:
$(function() {
$("#get_vulns_from_family").submit(function(event) {
var family_text = $("#family_content").val();
var family_data = {"family": family_text};
$.ajax({
url: "/template_conf/get_vulns_from_family",
type: "POST",
data: family_data,
success: function(response) {
console.log(response);
},
error: function(response) {
console.log("failed!");
}
});
// prevent default posting of form
event.preventDefault();
});
});
在对应于url /template_conf/get_vulns_from_family
的Django方法中,我尝试了这个:
def get_vuln_from_family(request):
family = request.POST['family']
# some other operations to get value for variable "json_data"
return HttpResponse(simplejson.dumps(json_data))
但是django说:MultiValueDictKeyError: "Key 'family' not found in <QueryDict: {}>"
,这意味着POST字典是空的。
我使用错误的方式获取发布数据吗?如果是这样我该怎么办?感谢。
答案 0 :(得分:10)
您的网址"/template_conf/get_vulns_from_family"
缺少尾随斜杠。 django通常会将此重定向到"/template_conf/get_vulns_from_family/"
,删除POST
数据
答案 1 :(得分:0)
如果启用了CSRF,那么简单的ajax帖子就无效了。您将不得不添加csrf标记并将其设置为ajax请求标头。
对于Ajax POST请求,您必须在每次POST请求时将CSRF令牌作为POST数据传递。因此,您必须首先获得CSRF令牌。由于您已启用CSRF保护,因此您将从csrftoken cookie获取令牌。默认情况下,CSRF令牌cookie名为csrftoken。获取令牌非常简单,可以使用下面的代码片段来实现。
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]);
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
function csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
function sameOrigin(url) {
var host = document.location.host; // host + port
var protocol = document.location.protocol;
var sr_origin = '//' + host;
var origin = protocol + sr_origin;
return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
(url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
!(/^(\/\/|http:|https:).*/.test(url));
}
$(function() {
$("#person_form_id").submit(function(event){
event.preventDefault();
$.ajax({
type:$(this).attr('method'),
url:"",
data:$(this).serialize(),
success: function(){
$('#message').html("<h2 style='color:green;'>Person Form Submitted!</h2>")
},
error: function(){
$('#message').html("<h2 style='color:red;'>Can't submit form</h2>")
}
});
return false;
});
});
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
// Send the token to same-origin, relative URLs only.
// Send the token only if the method warrants CSRF protection
// Using the CSRFToken value acquired earlier
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});