检索和存储响应(状态代码)- PHP

Retrieving and Storing Response (Status Code) - PHP

所以,我想了解 HTTP 状态代码,并且我想连接到数据库。我的问题是从我的 php 函数中得到正确的响应。

test.php

<?php
// try catch statement to connect to database through getConnection() function in dbConn.php file

try {
    require_once("dbConn.php");
    $dbConn = getConnection();
    // if getConnection() returned $conn (a connection), then $response_array["status"] = "success"
    // if getConnection() returned 503 status code from the catch block, then $response_array["status"] = "failed"
    // $response_array["status"] = "success";
} catch (Exception $e) {
    // if the file does not exist, then $response_array["status"] = "notFound"
    // http_response_code(404);
    // $response_array["status"] = "notFound";
}

header("Content-type: application/json");
echo json_encode($response_array);

dbConn.php

<?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);
        http_response_code(503);
    }
}

我最近将 dbConn.php 中的 getConnection() 函数更改为 return 连接数据库失败时的 503 状态代码,但我无法在我的 test.php 文件。我希望检索连接是否有效以将成功或失败的消息存储到 $response_array["status"],然后将其发送回 ajax 处理程序以触发成功或错误方法。如果找不到文件,我也想对 404 状态代码执行相同的操作。

最初的问题是在这里问的:

AJAX 部分:

$.ajax({
  type: "post",
  dataType: "text",
  url: "test.php",

  statusCode: {
    404: function(message) {
      alert(message);
    }
  } 

  success: function(data) {
    alert('Success');
  }
});

PHP 部分:

// sent a 404...
http_response_code(404);
echo 'File not found';
exit;