【发布时间】:2016-04-04 14:35:30
【问题描述】:
我正在尝试让 Ajax POST 将数据发送到我的视图,以便我可以在那里操作我的数据,当我单击类 up-arrow 的 div 时。
问题是,当我单击该 div 并在我的视图文件中打印 request.POST 时,我得到一个包含 <QueryDict: {}> 的 POST 对象。空的!我似乎无法弄清楚为什么我的 POST 请求没有发送我的数据。
这是我的 HTML...
{% for i in post.posts %}
<li>
<div>
<div class='up-arrow'>
</div>
{{i}}
</div>
</li>
{% 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(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'
我也得到一个“失败”alert。
如何通过POST 请求将我的数据发送到我的视图,然后访问其中的数据?
【问题讨论】:
-
你能通过开发者工具查看post请求中包含的内容吗?在网络标签下
-
你试过
JSON.stringify({'dane': 123456789101112})吗?传递 JSON 时,它必须是一个字符串。请参阅:stackoverflow.com/questions/32570523/… 这可能不是您的问题,但需要考虑。
标签: javascript jquery ajax django