Php Ajax响应格式
我的网站有一个用户注册,点击注册按钮时会执行一个ajax请求。此请求处理验证以及将用户添加到数据库。我有一切工作,但我有一个小问题,我想解决。在我的错误处理中,响应可能返回一个400 http状态代码,其中包含一个缺少的字段或无效的字段消息。对于这些消息,我希望在一行中显示换行符之前的句子,然后在新行中显示换行符之后的句子 PHP:Php Ajax响应格式,php,jquery,ajax,Php,Jquery,Ajax,我的网站有一个用户注册,点击注册按钮时会执行一个ajax请求。此请求处理验证以及将用户添加到数据库。我有一切工作,但我有一个小问题,我想解决。在我的错误处理中,响应可能返回一个400 http状态代码,其中包含一个缺少的字段或无效的字段消息。对于这些消息,我希望在一行中显示换行符之前的句子,然后在新行中显示换行符之后的句子 PHP: // If all the previous steps are valid and variables are set, try to run the SQL q
// If all the previous steps are valid and variables are set, try to run the SQL query to make new account.
if (isset($firstname) && isset($surname) && isset($email) && isset($usernameSignup) && isset($passwordHash)) {
try {
// code to add user to database not included but is here
} catch (PDOException $e) {
http_response_code(400);
die("Email or Username Already Exists.\n Make sure these fields are valid before trying again.");
}
} else {
http_response_code(400);
die("Missing Field(s).\n Make sure there are no empty fields before trying again.");
}
$.ajax({
type: "post",
url: "userRegistration.php",
data: {
},
dataType: "json",
success: function(xhr) {
// Success handler code
}
},
error: function(xhr) {
// Default error handler code
},
statusCode: {
400: function(res) {
console.log(res);
console.log(res.status);
console.log(res.responseText);
$("#loadingIcon").addClass("d-none");
$("#errorResponse").removeClass("d-none");
$("#errorMessage").text("An error occured: " + res.responseText);
}
}
});
JS:
// If all the previous steps are valid and variables are set, try to run the SQL query to make new account.
if (isset($firstname) && isset($surname) && isset($email) && isset($usernameSignup) && isset($passwordHash)) {
try {
// code to add user to database not included but is here
} catch (PDOException $e) {
http_response_code(400);
die("Email or Username Already Exists.\n Make sure these fields are valid before trying again.");
}
} else {
http_response_code(400);
die("Missing Field(s).\n Make sure there are no empty fields before trying again.");
}
$.ajax({
type: "post",
url: "userRegistration.php",
data: {
},
dataType: "json",
success: function(xhr) {
// Success handler code
}
},
error: function(xhr) {
// Default error handler code
},
statusCode: {
400: function(res) {
console.log(res);
console.log(res.status);
console.log(res.responseText);
$("#loadingIcon").addClass("d-none");
$("#errorResponse").removeClass("d-none");
$("#errorMessage").text("An error occured: " + res.responseText);
}
}
});
我希望“在重试之前确保没有空字段”位于新行。如果可能的话,我还希望以粗体显示“缺少的字段” 将html标记添加到文本中:
die("<b>Missing Field(s).</b><br /> Make sure there are no empty fields before trying again.");
die(“缺少字段)。
在重试之前,确保没有空字段。”;
然后更改您的js:
$("#errorMessage").html("An error occured:<br />" + res.responseText);
$(“#errorMessage”).html(“发生错误:
”+res.responseText);
您需要使用html()
函数,因为您的文本包含html标记