当我的 ajax 请求正在执行时(对于 post 方法),我试图通过 PHP 连接到我的数据库,但是如果无法连接,我想向我的用户显示一条错误消息。我可以在连接时显示成功消息,但我想知道是否有办法手动抛出 catch 块,以便我知道我的代码正在运行,如果用户无法连接到,则会向用户显示一条消息数据库(目前使用 console.log 进行测试)。
JS
$.ajax({
type: "post",
url: "test.php",
dataType: "json",
error: function(data) {
console.log(data.status);
console.log("Not Successful Test");
if (data.status == "connectionError") {
console.log("Didn't connect to database");
} else {
console.log("Other");
}
},
success: function(data) {
console.log(data.status);
console.log("Successful Test");
if (data.status == "success") {
console.log("Connected to Database");
} else {
console.log("Other");
}
}
});
测试.php
try {
require_once("dbConn.php");
$dbConn = getConnection();
$response_array["status"] = "success";
} catch (Exception $e) {
$response_array["status"] = "connectionError"; // Want to display this response in JS code
}
header("Content-type: application/json");
echo json_encode($response_array);
dbConn.php
function getConnection()
{
try {
$conn = new PDO(
"localhost=localhost;dbname=dbname",
"username",
"password"
);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
} catch (Exception $e) {
throw new Exception("Connection error " . $e->getMessage(), 0, $e);
}
}
解决方案 test.php
try {
require_once("dbConn.php");
$dbConn = getConnection();
$response_array["status"] = "success";
} catch (Exception $e) {
// Added http response code then die() with message
http_response_code(503);
die("<b>Server Error.</b><br/> This service is currently unavailable. Please try again at a later time.");
}
header("Content-type: application/json");
echo json_encode($response_array);
陪伴而非守候