gpt4 book ai didi

php - 使用 jquery 和 php 检查登录表单并显示错误消息

转载 作者:行者123 更新时间:2023-12-02 18:48:55 25 4
gpt4 key购买 nike

我正在尝试检查使用 jquery 和 php 提交的表单。我正在向服务器发出 .ajax 请求,以验证数据是否已输入表单并根据服务器的回调响应执行不同的操作。 例如,如果未输入名字或姓氏,则显示错误消息。

问题是,当两者都没有输入时,回调会同时返回消息名字和姓氏,而不会显示错误消息。

        // JavaScript Document
$(function(){
$("#form").submit(function(event){
$("#name_alert").css("display,none");
event.preventDefault();
$.ajax({
url:'functions/register_user.php',
type:"POST",
data:$(this).serialize(),
success:function(data){
if(data=='true')
{
$("#form").effect("shake", {times:2}, 600);
$("#alert").fadeIn("slow");
$("#note").fadeIn("slow").html('<strong>ERROR</strong>: Your details were incorrect.');
}
if(data=='name'){
$("#name_alert").fadeIn("fast").effect("shake", {times:1}, 600);
$("#name_note").html('<strong>ERROR</strong>: Your first name must be in the range
of 2 to 20 characters long.');
}
if(data=='surname'){
$("#surname_alert").fadeIn("fast").effect("shake", {times:1}, 600);
$("#surname_note").html('<strong>ERROR</strong>: Your surname must be in the range
of 2 to 20 characters long.');
}
else {
$("#name_alert").fadeOut("fast");
$("#note").html('<strong>PERFECT</strong>: You may proceed. Good times.');
}
}
});
});
});

服务器端代码正在检查表单中的字段是否为空,并回显相应的消息,例如名字或姓氏。然后 jquery 根据服务器的输出显示正确的消息。

最佳答案

这是一个如何完成此操作的示例。我尽量保持简单:

服务器端响应示例:

// If the posted value was left empty or not received return an error in json format.
If ( empty($_POST['value']) )
{
echo json_encode(
array('status' => false, 'error' => 'The value cannot be left empty'));
return true;
}

客户端ajax示例:

$.ajax({
url: "/url/to/your/script",
type: "POST",
data: 'your=data',
dataType: "json",
success: function(reply){
// If the reply.status is false, show the error status message
if( !reply.status ){
alert( reply.error );
}
}
});

关于php - 使用 jquery 和 php 检查登录表单并显示错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16036142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com