preventDefault函数不适用于Ajax/Form Handling


preventDefault function not working with Ajax/Form Handling

下面的表单我一直试图通过Ajax函数而不是通过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>

下面是我这样做的ajax代码

$(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();

});

但是,表单似乎完全忽略了所有内容,并将其传递到操作中,而不是阻止默认,我不太确定为什么。实际的install.php函数工作正常,但我只是不明白为什么它不通过Ajax。

preventDefault停止事件冒泡,但取消自身事件。您必须从函数返回false才能取消默认行为(打开表单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;
});

另外更好的实践是处理sumbit按钮click,但表单事件"提交"。