如何在jquery.post调用上停止表单提交?

时间:2013-07-31 07:36:02

标签: javascript jquery python django post

HTML

<form action="/jobseeker/profile/" method="post" id="langForm">     
    <input type="hidden" name="curform" value="langform">
    <div class="control-group">
        <label class="control-label">Language Name</label>
        <div class="controls">
            <input id="languageadd" maxlength="120" name="language" type="text" required/>
        </div>
    </div>
    <input class="btn btn-success" type="submit" value="save" />
</form>

jquery脚本

$("#langForm").on("submit", function(event){    
    $.post('/jobseeker/profile/', $(this).serialize(),
    function(data){
        alert('AJAX successful');
        //CreateRow(jdata);
    }, "json"); 
    event.preventDefault(); 
});

views.py for / jobseeker / profile /

def addlang(request):
    #curform=request.POST['curform']
    md=Languages()
    for i in request.POST.keys():
        if i=='curform':continue
        setattr(md,i,request.POST[i])
    md.save()
    n={ 
            "pk": md.pk,
            "lang":md.language,
            "read":md.read,
            "speak":md.speak,
            "write":md.write            
    }
    return HttpResponse(json.dumps(n), mimetype="application/json")

当我点击提交按钮阻止默认不起作用并且整个表单提交发生

after submit button click

3 个答案:

答案 0 :(得分:2)

尝试使用return false;

 $("#langForm").on("submit", function(event){    
 $.post('/jobseeker/profile/', $(this).serialize(),
 function(data){
    alert('AJAX successful');
    //CreateRow(jdata);
 }, "json"); 
 return false;
});

答案 1 :(得分:1)

尝试删除HTML表单中指定的action="/jobseeker/profile/"

试试这个

$("#langForm").submit(function(event){    
    $.post('/jobseeker/profile/', $(this).serialize(),
    function(data){

        /* stop form from submitting normally */
        event.preventDefault();

        alert('AJAX successful');
        //CreateRow(jdata);
    }, "json"); 
    event.preventDefault(); 
});

event.preventDefault();将停止表单的默认提交。

答案 2 :(得分:0)

preventDefault()放在最前面,return false放在最后。

$("#langForm").on("submit", function (event) {
    event.preventDefault();
    $.post('/jobseeker/profile/', $(this).serialize(),
        function (data) {
            alert('AJAX successful');
            //CreateRow(jdata);
        }, "json");
    return false;
});