Python django ajax发布空数据
我正在尝试使用ajax将数据发布到django视图。我没有错误,只是没有返回数据。 以下是我的javascript ajax:Python django ajax发布空数据,python,ajax,django,Python,Ajax,Django,我正在尝试使用ajax将数据发布到django视图。我没有错误,只是没有返回数据。 以下是我的javascript ajax: function PostGoal(){ console.log('POSTGOAL!!!') data_s = { 'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val(), 'goal': { 'name':'gg','bo
function PostGoal(){
console.log('POSTGOAL!!!')
data_s = {
'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val(),
'goal': { 'name':'gg','box':'sasa' }
}
$.ajax({
method: "POST",
url: "http://127.0.0.1:8000/",//"{% url 'home' %}",//"/",//"{% url 'home' %}",
contentType: 'application/json',
//data: JSON.stringify(data_s),
data: {'QQww': "1"},
//dataType: 'json',//expected type of response
success: function (data) {
console.log('aa'+JSON.stringify(data))
},
error: function(xhr,errmsg,err){
console.log('err: '+JSON.stringify(err)+' msg:'+errmsg)
}
});
}
以下是我的查看功能:
def analyzer(request):
if request.method == 'POST':
post_data = request.POST
print(post_data)
print (' ajax:',request.is_ajax())
布尔request.is_ajax is ajax始终为False request.data或request.POST.data不存在,GET:request.GET为空。但是,我可以在终端的日志中看到:
[22/Mar/2018 22:15:26] "GET /?QQww=1 HTTP/1.1" 200 9746
那么,数据基本上是在url中解析的?提前感谢。我在其他一些帖子中读到,“方法”是指定调用的正确字段。由于某些原因,参数“method”不起作用,正确的字段为“type”:
$.ajaxSetup({
headers: { "X-CSRFToken": '{{csrf_token}}' }
});
$.ajax({
type: "POST",
url: "http://127.0.0.1:8000/",//"{% url 'home' %}",//"/",//"{% url 'home' %}",
contentType: 'application/json',
//data: JSON.stringify(data_s),
data: {'QQww': "1"},
//dataType: 'json',//expected type of response
success: function (data) {
console.log('aa'+JSON.stringify(data))
},
error: function(xhr,errmsg,err){
console.log('err: '+JSON.stringify(err)+' msg:'+errmsg)
}
});
html按钮的类型也必须为“按钮”而不是“提交”:
<button type="button" class="btn btn-primary btn-large" id="yesbtn" name="yesbtn" value="yesbtn" onclick="PostGoal();">Yes »</button>
我希望它能有所帮助。您应该调查为什么在指定POST时它会被视为GET。thing也是request。GET是空的,所以数据甚至不在GET中
'Forbidden (CSRF token missing or incorrect.): /'