duandiao3961 2014-11-02 16:49
浏览 87

preventDefault函数无法使用Ajax / Form Handling

The following form I've been trying to pass through an Ajax function rather than through the action/PHP.

    <section class="registration">
    <form name="userRegistration" method="post" id="userregister" action="install.php">

        <label for="username">Username</label>
        <input type="text" name="username" id="username" value="admin">



        <label for="username">Author Name</label>
        <input type="text" name="authname" id="authname" placeholder="Example: John Doe">


        <label for="password">Password</label>
        <input type="password" name="pass" id="pass" value="">    



        <label for="sitetitle">Site Title</label>
        <input type="text" name="sitetitle" id="sitetitle" >


        <label for="sitedesc">Site Description</label>
        <input type="text" name="sitedesc" id="sitedesc" >



        <label for="server">Server</label>
        <input type="text" name="server" id="server" placeholder="Example: localhost">


        <label for="database">Database</label>
        <input type="text" name="database" id="database" >   



        <label for="dbun">DB Username</label>
        <input type="text" name="dbun" id="dbun" >



        <label for="dbpw">DB Password</label>
        <input type="password" name="dbpw" id="dbpw" >

        <input type="submit" />
    </form>

Below is my ajax code for doing so.

$(document).on('submit', '#userregister form', function(e) {
 $.ajax({
    url: $(this).attr('action'),
    type: $(this).attr('method'),
    data: $(this).serialize(),
    success: function(html) {
    alert('ok');
    }
});
e.preventDefault();

});

But instead of preventing the default, the form seems to completely ignore everything and pass it through the action, and I'm not too sure why. The actual install.php functions work right, but I'm just stumped as to why its not passing through the Ajax.

  • 写回答

1条回答 默认 最新

  • duanjinchen5296 2014-11-02 17:23
    关注

    preventDefault stopped event bubbling, but cancel self event. You must return false from your function for cancel default behavior (opening form url):

    $(document).on("submit", "#userregister form", function (e) {
        $.ajax({
            url: $(this).attr('action'),
            type: $(this).attr('method'),
            data: $(this).serialize(),
            success: function(html) {
                alert('ok');
            }
        });
        e.preventDefault();
        return false;
    });
    

    Also better practic is handling sumbit button click, but form event "submit".

    评论

报告相同问题?