Javascript 处理Ajax响应

Javascript 处理Ajax响应,javascript,php,jquery,ajax,Javascript,Php,Jquery,Ajax,我正在为我的网站创建一个用户注册表单,并使用ajax来处理服务器端的过程。我的问题是如何处理来自php代码的响应。在服务器端执行时,可能的响应包括成功(注册用户)、数据库连接错误、空字段错误或执行sql查询失败(输入已存在于唯一的sql字段中,例如用户名、电子邮件)。我想知道我如何能够得到正确的响应,以便向用户显示消息。我所拥有的: JS $.ajax({ type: "post", url: "userRegistration.php", data: {

我正在为我的网站创建一个用户注册表单,并使用ajax来处理服务器端的过程。我的问题是如何处理来自php代码的响应。在服务器端执行时,可能的响应包括成功(注册用户)、数据库连接错误、空字段错误或执行sql查询失败(输入已存在于唯一的sql字段中,例如用户名、电子邮件)。我想知道我如何能够得到正确的响应,以便向用户显示消息。我所拥有的:

JS

  $.ajax({
    type: "post",
    url: "userRegistration.php",
    data: {
      firstname: firstname,
      surname: surname,
      email: email,
      usernameSignup: username,
      passwordSignup: password,
      passwordConfirm: passwordConfirm
    },
    dataType: "json",
    success: function(data) {
      console.log(data.status);
      if (data.status == "success") {
        console.log("Registration was successful");
        //Do success stuff
      } else if (data.status == "error") {
        console.log("Didn't Execute Query");
        // Do error stuff
      } else if (data.status == "connectionError") {
        console.log("Failed to connect to database");
        // Do error stuff
      } else {
        console.log("Empty fields");
        // Do error stuff
    }
  });
PHP

<?php
// try catch statement to connect to database through getConnection() function in dbConn.php file
try {
    // try to connect to database
    require_once("dbConn.php");
    $dbConn = getConnection();
} catch (Exception $e) {
    // database connect error
    //echo "A problem occured: " . $e->getMessage();
    $response_array["status"] = "connectionError";
}

// Form validation for POST method to check fields are not empty
if (!empty($_POST['firstname'])) {
    $firstname = filter_has_var(INPUT_POST, 'firstname') ? $_POST['firstname'] : null;
    $firstname = trim($firstname);
} else {
    echo "A first name must be entered.<br/>";
}

// Same validation for other fields

// If all the previous steps are valid and variables are set, try to run the SQL query to make new account.
if (!empty($firstname) && !empty($surname) && !empty($email) && !empty($usernameSignup) && !empty($passwordHash)) {
    try {
        $sqlQuery = "INSERT INTO GH_users (firstname, surname, email, accountConfirmed, username, passwordHash)
        VALUES ('$firstname', '$surname', '$email', 0, '$usernameSignup', '$passwordHash')";
        $execute = $dbConn->exec($sqlQuery);
        $response_array["status"] = "success";
    } catch (PDOException $e) {
        // failure to execute error
        //echo $sqlQuery . "<br>" . $e->getMessage();
        $response_array["status"] = "error";
    }
} else {
    // empty field(s) error
    $response_array["status"] = "empty";
}

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

当检测到错误时,需要跳过所有剩余的代码,直到发送JSON响应。例如,如果您得到一个
连接错误
,则不应尝试执行该查询;这将得到一个错误,并将
$response\u数组['status']='connectionError'
替换为
$response\u数组['status]='error'
,因此您将报告错误类型的错误

此外,表单验证错误需要在JSON响应中返回,而不是直接回显

实现这一点的一种方法是嵌套
try/catch
语句

<?php
// try catch statement to connect to database through getConnection() function in dbConn.php file
try {
    // try to connect to database
    require_once("dbConn.php");
    $dbConn = getConnection();

    // Form validation for POST method to check fields are not empty
    if (!empty($_POST['firstname'])) {
        $firstname = filter_has_var(INPUT_POST, 'firstname') ? $_POST['firstname'] : null;
        $firstname = trim($firstname);
    } else {
        $response_array["status"] = "validationError";
        $response_array["message"] = "A first name must be entered.";
    }

    // Same validation for other fields

    // If all the previous steps are valid and variables are set, try to run the SQL query to make new account.
    if (!empty($firstname) && !empty($surname) && !empty($email) && !empty($usernameSignup) && !empty($passwordHash)) {
        try {
            $sqlQuery = "INSERT INTO GH_users (firstname, surname, email, accountConfirmed, username, passwordHash)
        VALUES ('$firstname', '$surname', '$email', 0, '$usernameSignup', '$passwordHash')";
            $execute = $dbConn->exec($sqlQuery);
            $response_array["status"] = "success";
        } catch (PDOException $e) {
            // failure to execute error
            //echo $sqlQuery . "<br>" . $e->getMessage();
            $response_array["status"] = "error";
        }
    } else {
        // empty field(s) error
        $response_array["status"] = "empty";
    }

} catch (Exception $e) {
    // database connect error
    //echo "A problem occured: " . $e->getMessage();
    $response_array["status"] = "connectionError";
}

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

您应该倾向于将准备好的语句与参数化查询一起使用,以防止SQL注入。