How to POST a django form with AJAX & jQuery

原文地址:http://stackoverflow.com/questions/7335780/how-to-post-a-django-form-with-ajax-jquery

html:

<script type="text/javascript">
    var frm = $('#FORM-ID');
    frm.submit(function () {
        $.ajax({
            type: frm.attr('method'),
            url: frm.attr('action'),
            data: frm.serialize(),
            success: function (data) {
                $("#SOME-DIV").html(data);
            },
            error: function(data) {
               // Display form validation errors like the image below
               var form_errors = data.msg;
              
               for(var fieldname in form_errors) {
               var error = form_errors[fieldname];
               $('#id_'+fieldname).parent().addClass("has-error");
               if ($('#id_'+fieldname).nextAll().length < 1)
                $('#form input[name='+fieldname+']').after("<span class='help-block'>"+error+"</span>");
              }
            }
        });
        return false;
    });
</script>

view:

 
    if request.is_ajax() and request.method == "POST":
        form = TestForm(request.POST, instance=test)
        if form.is_valid():
            form.save()
            results[ 'status' ] =True 
            results['msg'] = u'原因'
            return HttpResponse( simplejson.dumps( results ), mimetype='application/json' )
        else:
            response_data = {"msg":dict(form.errors), "status":"error"}
            return HttpResponse(json.dumps(response_data), mimetype='application/json')  

form error显示效果:

posted @ 2013-12-09 15:54  blue_whale  阅读(318)  评论(0编辑  收藏  举报