使用jQuery提交表单,然后更新表单以显示错误,不允许再次提交表单


Submitting form with jQuery, then updating the form to show errors, does not allow form to be submitted again

我正在通过PHP函数显示一个表单:

function getLoginForm($errors = false) {
    $output .= '<form action="#" name="login" method="post" />';
        $output .= '<h2>Sign in to ' . APPNAME . '</h2>';
        $output .= '<div class="field">';
            $output .= '<label for="username">Username</label>';
            $output .= '<input type="text" id="username" name="username"' . getPostValue('username')  . ' />';
            if(isset($errors['username'])) {
                $output .= '<div class="help">' . $errors['username'] . '</div>';
            }
        $output .= '</div>';
        $output .= '<div class="field">';
            $output .= '<label for="password">Password</label>';
            $output .= '<input type="password" id="password" name="password"' . getPostValue('password')  . ' />';
            if(isset($errors['passsword'])) {
                $output .= '<div class="help">' . $errors['username'] . '</div>';
            }
        $output .= '</div>';
        $output .= '<div class="message"></div>';
        $output .= '<div class="button">';
            $output .= '<button type="button" name="commit">Login</button>';
        $output .= '</div>';
    $output .= '</form>';
    return $output;
}
然后,我有一个文件,该表单通过jQuery发送到该文件以处理值。如果处理器发现错误,它将使用错误数组作为参数调用getLoginForm函数。这样,当表单重新显示时,错误就会显示在字段下面。

事情是,处理器文件返回整个形式,它得到交换与旧的形式,这就是我认为是问题所在。当我尝试再次提交表单时,它没有做任何事情,因为jQuery一定不知道这个新创建的表单。

解决这个问题我有什么选择?

谢谢,瑞安

<标题> 更新jQuery提交处理程序:
$('form').submit(function(e){
        var formElement = $(this);
        var data = formElement.serialize();
        var page = 'process.php?p=' + formElement.attr('name');
        formElement.find('button[name=commit]').attr('disabled', 'disabled').addClass('disabled');
        formElement.find('.message').html('<div class="pending">Sending your request... please wait...</div>');
        $.post(page, data, function(response) {
            formElement.html(response);
        });
        e.preventDefault();
    });

尝试使用"live()"来绑定动态创建对象的事件。

要做到这一点,您可以将代码更改为:
$('form').live('submit', function() { ...

使用"live"来绑定事件将绑定到所有匹配jQuery选择器的当前和未来元素。由于您正在覆盖表单,因此这是一个新元素,因此您当前的代码将不会绑定到提交事件。