无法阻止表单ajax提交上的默认值

时间:2014-03-14 20:20:33

标签: jquery

单击提交后,我无法转到Post URL。我该怎么调试呢?在表单打开提交URL之前,我很快就能看到console.log上的错误,但我无法阻止默认表单提交以查看错误是什么......

$('#done').click(function(e){
        var failed = 0;

        formData=$("form").serializeArray();        
        for(var i=0; i<formData.length;i++){
            console.log(i+': ' +formData[i].value);
            if(formData[i].value=="") {
                failed =1;
            } 
        }

        if(failed){
            console.log('failed');

        } else {
            console.log('success');
            var loginFormURL = form.find('form').attr("action");
            //return false;
            $.ajax({
                url : loginFormURL, //need to tell which URL to submit to
                type: "POST",
                data : formData, //serialized data
                success:function() {
                    console.log("succeeded"); 
                    return false;
                },
                error: function() {
                    console.log("failed");
                    return false;
                }
            });
            return false;
        }


    });

1 个答案:

答案 0 :(得分:1)

您要做的是在其他条件中设置return false

else{
//some code
          return false;
                }
            });
            return false;
}

但是,您应该做的是使用e.preventDefault()作为:

来阻止点击
$('#done').click(function(e){
        e.preventDefault();
        var failed = 0;
        formData=$("form").serializeArray();    
        //rest of the code here

或者,您可以在函数末尾返回false,如此;

$('#done').click(function(e){
        var failed = 0;

        formData=$("form").serializeArray();        
        for(var i=0; i<formData.length;i++){
            console.log(i+': ' +formData[i].value);
            if(formData[i].value=="") {
                failed =1;
            } 
        }

        if(failed){
            console.log('failed');

        } else {
            console.log('success');
            var loginFormURL = form.find('form').attr("action");
            //return false;
            $.ajax({
                url : loginFormURL, //need to tell which URL to submit to
                type: "POST",
                data : formData, //serialized data
                success:function() {
                    console.log("succeeded"); 
                    return false;
                },
                error: function() {
                    console.log("failed");
                    return false;
                }
            });
        }
  return false; //<------ it goes here
}