在Django视图中调用’request.POST’时,Ajax POST不发送数据
我正在尝试获取Ajax POST
以将数据发送到我的视图,这样我就可以在那里操作我的数据,当我点击带有类up-arrow
的div
时。
问题是,当我在视图文件中单击所述div并打印request.POST
时,我得到一个包含的
POST
对象。 空! 我似乎无法弄清楚为什么我的POST请求没有发送我的数据。
这是我的HTML …
{% for i in post.posts %} {{i}} {% endfor %}
这是我的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; } })
这是我的看法……
class VoteUpPost(View): def post(self, request): print(request.POST) return JsonResponse({'status': True})
这是我的url路线……
url(r'^voteuppost$', VoteUpPost.as_view()),
我尝试过的事情……
1)我使用GET
而不是POST
,我可以使用request.GET.get('dane')
获取数据值
1)尝试使用request.POST.data
和request.POST.DATA
并获取以下内容… AttributeError: 'QueryDict' object has no attribute 'data'
,我也得到’fail’ alert
。
如何通过POST
请求将数据发送到我的视图,然后访问其中的数据?
使用application/json
发布JSON数据时,您需要使用request.body
而不是request.POST
。
像这样:
class VoteUpPost(View): def post(self, request): print(request.body) data = json.loads(request.body) return JsonResponse({'status': True})
同样正如Jacques所提到的,请确保更新您的js以传递JSON字符串。
更改:
data: {'dane': 123456789101112},
至:
data: JSON.stringify({'dane': 123456789101112}),
Django请求只能将application / x-www-form-urlencoded和multipart / form-data解析为request.POST
。 对于其他内容类型,您必须使用request.body
属性。 对于内容类型的断言,您可以从request.META.get('CONTENT_TYPE')
获取内容类型
def sample_view(request): if request.META.get('CONTENT-TYPE') == 'application/json': data = json.loads(request.body) return JsonResponse({'any-message':'Hello'})