在Django视图中调用"request.POST"时,Ajax POST不发送数据 [英] Ajax POST not sending data when calling 'request.POST' in Django view
问题描述
我试图获取Ajax POST
来将数据发送到视图,以便在单击类up-arrow
的div
时可以在那里处理数据.
I am attempting to get an Ajax POST
to to send data to my view so I can manipulate my data there, when I click on a div
with class up-arrow
.
问题是,当我单击所说的div并在视图文件中打印request.POST
时,我得到的是一个包含<QueryDict: {}>
的POST
对象.空的!我似乎无法弄清楚为什么我的POST请求没有通过发送我的数据.
Problem is, when I click said div and print request.POST
in my view file, I am getting a POST
object that contains <QueryDict: {}>
. Empty! I can't seem to figure out why my the POST request isn't sending my data through.
这是我的HTML ...
Here is my HTML...
{% for i in post.posts %}
<li>
<div>
<div class='up-arrow'>
</div>
{{i}}
</div>
</li>
{% endfor %}
这是我的AJAX/jQuery ...
Here is my AJAX/jQuery...
$(document).ready(function(){
$('.up-arrow').click(function(){
$(this).hide()
console.log('click')
$.ajax({
headers: {
'Content-Type':'application/json',
'X-CSRFToken': getCookie('csrftoken')
},
url: 'voteuppost',
type: 'POST',
data: {'dane': 123456789101112},
success: function(data) {
alert('success!')
},
error: function(){
alert('fail')
}
})
return false
});
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;
}
})
这是我的观点...
Here is my view...
class VoteUpPost(View):
def post(self, request):
print(request.POST)
return JsonResponse({'status': True})
这是我的网址路由...
Here is my url route...
url(r'^voteuppost$', VoteUpPost.as_view()),
我尝试过的事情...
Things I have tried...
1)我使用GET
而不是POST
,并且能够使用request.GET.get('dane')
1) I used GET
instead of POST
and I am able to get the data value using request.GET.get('dane')
1)尝试使用request.POST.data
和request.POST.DATA
并获得以下信息... AttributeError: 'QueryDict' object has no attribute 'data'
,我也得到了失败" alert
.
1) Tried using request.POST.data
and request.POST.DATA
and get the following... AttributeError: 'QueryDict' object has no attribute 'data'
and I also get a 'fail' alert
.
如何通过POST
请求将数据发送到视图中,然后访问其中的数据?
How do I send my data over to my view via a POST
request and then access the data within?
推荐答案
使用application/json
发布JSON数据时,您需要使用request.body
而不是request.POST
.
When posting JSON data with application/json
you need to use request.body
instead of request.POST
.
像这样:
class VoteUpPost(View):
def post(self, request):
print(request.body)
data = json.loads(request.body)
return JsonResponse({'status': True})
就像雅克提到的那样,请确保更新您的js以传递JSON字符串.
Also as Jacques mentioned, make sure to update your js to pass a JSON string.
更改:
data: {'dane': 123456789101112},
收件人:
data: JSON.stringify({'dane': 123456789101112}),
这篇关于在Django视图中调用"request.POST"时,Ajax POST不发送数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!