2016-01-18 21 views
1

我想提交一個表單數據使用jQuery的PHP。我不想在默認情況下提交它。代碼工作正常。我不知道在哪裏使用event.preventDefault();在哪裏使用preventDefault();在jquery中停止提交表單數據

下面是我的jQuery代碼

<script> 
$(function() { 
      $("#submit").click(function() { 
       var password = $("#password").val(); 
       var confirmPassword = $("#confirm_password").val(); 
       var dataString='password='+ password + 'confirmPassword='+ confirmPassword; 
       if (password != confirmPassword) { 
        alert("Passwords and Confirm Password Should match."); 
        return false; 
       } 

       else{ 

       $.ajax({ 
     type: "POST", 
     url: "update-password.php", 
     data: dataString, 
     success: function(result){ 
      alert(result) 

     } 
     }); 


    } 

    }); 

}); 

</script> 
+2

注意:不要使用'click'事件來控制表單提交。它被鍵盤表單提交繞過!始終使用'submit'事件。 –

+1

@TrueBlueAussie,然後發佈一個答案。 – Luke

回答

3

不要使用click事件來控制表單提交。它被鍵盤表單提交繞過!始終使用submit事件。

當你正在通過Ajax提交表單,你可以停止與e.preventDefault()

例如立即提交

$(function() { 
$("form").submit(function(e) { 
    e.preventDefault(); 
    var password = $("#password").val(); 
    var confirmPassword = $("#confirm_password").val(); 
    var dataString = 'password=' + password + 'confirmPassword=' + confirmPassword; 
    if (password != confirmPassword) { 
    alert("Passwords and Confirm Password Should match."); 
    } else { 
    $.ajax({ 
     type: "POST", 
     url: "update-password.php", 
     data: dataString, 
     success: function(result) { 
     alert(result) 
     } 
    }); 
    } 
}); 
}); 

注:如你沒有做什麼特別的東西與提交,你還不如不使用阿賈克斯,除非你需要。只是有條件地返回truefalse

返回錯誤與e.preventDefault()e.stopPropagation()相同。

例如

$(function() { 
$("form").submit(function() { 
    var password = $("#password").val(); 
    var confirmPassword = $("#confirm_password").val(); 
    var dataString = 'password=' + password + 'confirmPassword=' + confirmPassword; 
    if (password != confirmPassword) { 
    alert("Passwords and Confirm Password Should match."); 
    return false 
    } 
}); 
}); 

一般的建議:不要使用alert與用戶進行互動。請在頁面上顯示驗證消息。

+0

嗨,謝謝你的e.preventDefault();沒有爲我工作,但我只是修改了我的代碼,我改變了返回false的地方。我把它移到ajax alert之後,按我的要求工作。謝謝你的解釋。公認 –