【问题标题】:Print PHP message to form through Ajax/Jquery通过 Ajax/Jquery 打印 PHP 消息以形成表单
【发布时间】:2012-10-06 10:43:05
【问题描述】:

我有一个 jquery/bootstrap 表单。如果电子邮件地址已在使用中,我的 php 正在检查数据库。

如果电子邮件地址正在使用中,则会调用以下内容,但会转到新窗口。

echo'<p class="error">An account already exists for this email address. Please use a different email address</p>';

这一切都很好,但现在我希望错误消息显示在 Jquery 表单上。我似乎无法理解如何做到这一点。

我知道我必须使用这个处理程序,但我不知道将错误消息放在哪里,也不知道这段代码如何知道从 php.ini 读取哪个错误消息。此外,我希望错误消息显示在表单的电子邮件字段旁边

$(document).ready(function() {
    $('#form').submit(function() {
        $.ajax({
            type: 'POST',
            url: "process.php",
            data: dataString,
            success: function() {
            }
        })
        return false;
    });
});

【问题讨论】:

    标签: php jquery ajax forms


    【解决方案1】:

    可以在success 属性中处理错误消息。该函数可以接受data 参数(来自process.php 的响应)。

    success: function(data){
        //does data contain p.error?
        //get the contents of p.error, display it on the current page
    
        //for example:
        if( $(data).find("p.error.name").length ){
            //process name error here
            nameError = $(data).find("p.error.name").text();
            console.log(nameError);
        }
        if( $(data).find("p.error.email").length ){
            //process email error here
            emailError = $(data).find("p.error.email").text();
            console.log(emailError);
        }
    }
    

    上面定义的成功函数假设process.php看起来像这样:

    <div>
    <p class="error name">Please enter a name.</p>
    <p class="error email">Your email address is invalid.</p>
    
    <!-- some other stuff here -->
    </div>
    

    【讨论】:

    • 我明白了,所以“成功”将打印 process.php 打印的任何内容,即使它不是“成功”提交?我想我在这里对语义感到困惑。如何区分消息?假设我想要一个用于电子邮件,其他用于名字,姓氏。函数如何知道process.php中调用了哪一个?
    • 这是正确的——ajax调用的success属性是为了服务器的成功响应;它并不表示表单已成功提交(在验证等方面)。也许您可以修改process.php,使p.error 包含data- 属性或附加类来指示错误类型。在这种情况下,成功回调将寻找 p.error.namep.error.email
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多