gpt4 book ai didi

javascript - 关于AJAX、FORM和PHP

转载 作者:行者123 更新时间:2023-12-03 12:15:20 25 4
gpt4 key购买 nike

我的ajax代码如下所示,它检查注册表单用户名、电子邮件等...

jQuery(document).ready(function($) {
$("#formform").on('change', 'input',function(event){
var $form = $(this);
var $inputs = $form.find("input, select, button, textarea");
var serializedData = $form.serialize();
$inputs.prop("disabled", true);

request = $.ajax({
url: "/registration_check.php",
type: "post",
data: {formData:serializedData},
datetype: "JSON"
});
request.done(function (response, textStatus, jqXHR){
console.log(response);
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("error");
});
request.always(function () {
$inputs.prop("disabled", false);
});
event.preventDefault();
});
});

我的 PHP 看起来像这样:

$get_form_data=$_POST["formData"];
parse_str($get_form_data,$form_data);

if(isset($form_data["username"])){
if(strlen($form_data["username"])<5){
echo "Username must be at least 5 character";
}else{
if(ValidUserName($form_data["username"])){
if($checkUser->checkUserName(char_encoder($form_data["username"]))==true){
echo "Sorry this UserName Already Exist";
}else{
echo "UserName Available";
};
}else{
echo "Invalid Username";
}

}

}

现在,当 AJAX 响应中出现无效用户名时,如何禁用表单?

我虽然应该使用 return false..但不知道如何处理响应?

最佳答案

尝试使用以下格式,您可以处理成功事件中的响应:

var $form = $(this);
var serializedData = $form.serialize();
$.ajax({
type: "POST",
url: "/registration_check.php",
data: {
formData:serializedData
},
beforeSend: function () {
//do stuff like loading process until you get the response
},
success: function (resp) {
var obj = jQuery.parseJSON(resp);
//console.log(obj); // this will display response in console.
//do stuff here

},
error: function(e){
alert("Error in ajax call: "+e);
}

}); // complete AJAX

PHP 代码:

$array = array();
if (isset($form_data["username"])) {
if (strlen($form_data["username"]) < 5) {
$array['success'] = false;
$array['message'] = "Username must be at least 5 character";
} else {
if (ValidUserName($form_data["username"])) {
if ($checkUser->checkUserName(char_encoder($form_data["username"])) == true) {
$array['success'] = false;
$array['message'] = "Sorry this UserName Already Exist";
} else {
$array['success'] = true;
$array['message'] = "UserName Available";
}
} else {
$array['success'] = false;
$array['message'] = "Invalid Username";
}
}
echo json_encode($array);
}

关于javascript - 关于AJAX、FORM和PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24735501/

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