我正在尝试向 Django 视图发送一个简单的 POST 请求。初始 POST 失败后,数据将作为 GET 重新发送。我怎样才能成功发布?
javascript:
data = $('#submit_event').serialize() + '&status=new';
$.ajax({
data: data, // get the form data
type: $('#submt_event').attr('method'), // GET or POST
url: "/forms/visitor/1/event", // the file to call
success: function (response) {
console.log('post was a success')
}
})
html:
<form id='submit_event' action="{% url 'forms:event' visitor.id%}" method=
"POST">
{% csrf_token %}
Your Name (event title) <input type="text" name="title" id="title"><br>
<!-- removed some items for brevity -->
<button type="submit" value="save" name="save" onclick="saveEvent()">Save</button>
<button type="submit" value="delete" name="delete" onclick="deleteEvent()">Delete</button>
</form>
网址.py
urlpatterns = patterns('',
# visitor page
url(r'^visitor/(?P<visitor_id>\d+)/$', views.visitor, name='visitor'),
# page to post to
url(r'^visitor/(?P<visitor_id>\d+)/event', views.event, name='event'),
)
视图.py:
def event(request, visitor_id):
print 'event page reached'
print request.POST
return render_to_response('forms/all_visitor.html')
追溯:
event page reached
<QueryDict: {}>
Internal Server Error: /forms/visitor/1/event
Traceback (most recent call last):
File "/Users/arcarter/.virtualenvs/base/lib/python2.7/site-packages/django/core/handlers/base.py", line 115, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/Users/arcarter/code/facsearch/forms/views.py", line 56, in event
print request.POST['phone']
File "/Users/arcarter/.virtualenvs/base/lib/python2.7/site-packages/django/utils/datastructures.py", line 295, in __getitem__
raise MultiValueDictKeyError("Key %r not found in %r" % (key, self))
MultiValueDictKeyError: "Key 'phone' not found in <QueryDict: {}>"
[14/Aug/2013 13:31:25] "GET /forms/visitor/1/event?csrfmiddlewaretoken=gHA8G5ngIivsHoVlOw8S8rs3tP1ins1r&title=abc&location=&phone=&detail=&status=new HTTP/1.1" 500 10449
event page reached
<QueryDict: {u'title': [u'abc'], u'detail': [u''], u'phone': [u''], u'location': [u''], u'csrfmiddlewaretoken': [u'gHA8G5ngIivsHoVlOw8S8rs3tP1ins1r'], u'save': [u'save']}>
[14/Aug/2013 13:31:27] "POST /forms/visitor/1/event HTTP/1.1" 200 120
$.ajax 调用成功函数,之后服务器报告一个空的 . (此时数据被序列化。)但是,退出 $.ajax 后,浏览器重新发送为 GET,这是成功的。