我在Django模板中使用ajax POST 查询数据:{'action':'add'}
,但如果我在 views.py 中打印request.POST
则会显示控制台<QueryDict: {}>
。
但是萤火虫显示POST 302
和action=add
或action=remove
参数!所以我不明白为什么<QueryDict: {}>
是空的。请帮忙。
PS。如果我使用GET,它可以正常工作。
模板 show_event.html :
<form id="unfollow" {% if user not in event.users.all %}style="display:none;"{% endif %}>
<input type="hidden" value="{{ event.id }}" name="remove">
<button type="submit" class="btn btn-warning btn-block">{% trans "Remove from My events"%}</button>
</form>
<form id="follow" {% if user in event.users.all %}style="display:none;"{% endif %}>
<input type="hidden" value="{{ event.id }}" name="add">
<button type="submit" class="btn btn-primary btn-block">{% trans "Add to My events"%}</button>
</form>
$(document).on('submit','#unfollow', function(e){
e.preventDefault();
$.ajax({
type:"POST",
url:'/event/follow/{{ event.id }}/',
data: {'action':'remove'},
success:function(){
$('#unfollow').hide();
$('#follow').show();
}
})
});
$(document).on('submit','#follow', function(e){
e.preventDefault();
$.ajax({
type:"POST",
url:'/event/follow/{{ event.id }}/',
data: {'action':'add'},
success:function(){
$('#follow').hide();
$('#unfollow').show();
}
})
});
views.py:
def follow (request, event_id):
event = get_object_or_404(Event, id=event_id)
user = request.user
print request.POST
if request.method == 'POST':
print "post"
if request.POST['action'] == 'add':
print "add"
event.users.add(user)
event.save()
elif request.POST['action'] == 'remove':
print "remove"
event.users.remove(user)
event.save()
return HttpResponse('')
urls.py:
url(r'^event/follow/(?P<event_id>[0-9]+)/$', 'events.views.follow', name='follow')
答案 0 :(得分:2)
编辑(第二:修复表单标记以匹配URL):
实际上,正如您在标记中填写表单一样,有一种更简单的方法可以执行此操作:
var submitHandler = function(event) {
event.preventDefault();
event.stopPropagation();
var $form = $(this);
var url = $form.attr( "action" );
$.post(url, $form.serialize())
.done(function(data) {
if (data.following) {
$('#follow').hide();
$('#unfollow').show();
} else {
$('#follow').show();
$('#unfollow').hide();
}
});
};
$(document).on('submit','#unfollow', submitHandler);
$(document).on('submit','#follow', submitHandler);
您的标记应为:
<form id="unfollow" method="POST" action="{% url 'follow' event_id=event.id %}
{% if user not in event.users.all %}style="display:none;"{% endif %}>
{% csrf_token %}
<input type="hidden" value="remove" name="action">
<button type="submit" class="btn btn-warning btn-block">{% trans "Remove from My events"%}</button>
</form>
<form id="follow" method="POST" action="{% url 'follow' event_id=event.id %}
{% if user in event.users.all %}style="display:none;"{% endif %}>
{% csrf_token %}
<input type="hidden" value="add" name="action">
<button type="submit" class="btn btn-primary btn-block">{% trans "Add to My events"%}</button>
</form>
您的Django代码:
@require_http_methods(['POST'])
def follow (request, event_id):
event = get_object_or_404(Event, id=event_id)
user = request.user
action = request.POST.get('action', None)
following = False
if action == 'add':
event.users.add(user)
following = True
elif action == 'remove':
event.users.remove(user)
else:
return HttpResponseBadRequest('Unknown action: {}'.format(action))
event.save()
return JsonResponse({'following': following})
上一个回答:
根据您的jQuery版本,type
可能不再可用。尝试在AJAX配置中使用method: "POST"
而不是type: "POST"
。
http://api.jquery.com/jQuery.ajax/
此外,为了使您的标记更符合您在视图和JS中的预期,请将method="POST"
添加到表单元素。
旁注:
您可以通过QueryDict
通过get()
方法更好地处理非现有参数:
request.POST.get('action', None)
这将始终有效(除非request.POST
为None)。如果参数不存在,则返回默认值或第二个参数(在本例中为None
)。
request.POST['action']
如果action
不存在,则会因KeyError而失败。