我有一个简单的表单,我正在测试一个 ajax 调用。ajax.html 文件如下所示:
<form id="ajaxform" method="get" action="/polls/ajax/submit/">
<p>
<input type="text" name="input" id="input" />
<input type="submit" value="Submit" />
</p>
</form>
<script type="text/javascript">
$(document).ready(function () {
$('#ajaxform').ajaxForm({
success: ajaxformSubmit,
dataType: 'json',
clearForm: true,
resetForm: true
});
});
function ajaxformSubmit(responseText, statusText, xhr, $form) {
if (responseText['success'] == true) {
alert("Added item: " + responseText['pk']);
}
// returning false inhibits the browser from opening a "Save As" dialog.
return false;
}
</script>
它的 views.py 看起来像这样:
def ajax_test(request):
form = AjaxForm()
context = {
'form': form
}
return render(request, 'polls/ajax.html', context)
这个表单提交给这个 ajax 函数:
def AjaxSubmit( request ):
GET = request.GET
results = { 'success' : False }
form = AjaxForm( request.GET )
if form.is_valid():
print form.cleaned_data['input']
results['success'] = True
return HttpResponse( simplejson.dumps( results ), mimetype='application/json' )
urls.py 看起来像:
urlpatterns = patterns('',
url(r'^ajaxform/$', views.ajax_test, name='ajax-test'),
)
urlpatterns += patterns( 'polls.ajax',
(r'^ajax/submit/$', 'AjaxSubmit' ),
)
问题是,当我转到页面http://localhost:8000/polls/ajaxform/
并提交时,页面转到返回到 url 的 json:http://localhost:8000/polls/ajax/submit/?input=test
它应该保持在同一个表单页面上并使用 javascript 调用 json 响应。
我做了这个教程。
有什么我做错了吗?