表单提交转到新页面而不是根据django ajax表单加载

时间:2013-07-26 18:35:14

标签: jquery ajax django django-forms django-views

我有一个简单的表单,我正在测试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响应。

我做了this tutorial

我做错了吗?

1 个答案:

答案 0 :(得分:0)

我忘了添加javascript库:

<script src="http://malsup.github.com/jquery.form.js"></script> 

在那之后,它就像一个魅力。