Ajax-数据库连接处理 [英] Ajax - Database Connection Handling

查看:109
本文介绍了Ajax-数据库连接处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在执行ajax请求(对于post方法)时通过PHP连接到我的数据库,但是如果它无法连接,我想向我的用户显示一条错误消息.当它确实连接时,我可以显示成功消息,但是我想知道是否有一种方法可以手动抛出catch块,以便我知道我的代码正在工作,并且如果用户无法连接到该消息,则会向用户显示一条消息.数据库(当前使用console.log进行测试).

I'm trying to connect to my database via PHP when my ajax request is executing (for a post method), but I want to show my user an error message if it is unable to connect. I can show the success message when it does connect but I'm wondering if there is a way to manually throw the catch block so that I know my code is working and will display a message to the user if the user is unable to connect to the database (currently using console.log for testing purposes).

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");
    }
  }
});

test.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);

然后使用 JS

$.ajax({
  type: "post",
  url: "test.php",
  dataType: "json",
  error: function(data) {
    console.log(data.responseText);
  },
  success: function(data) {
    console.log(data.status);
    console.log("Successful Test");
    if (data.status == "success") {
      console.log("Connected to Database");
    } else {
      console.log("Other");
    }
  }
});

推荐答案

为了通知浏览器请求未成功,您需要传递一个非2xx的http响应代码.为了您的目的,您可以使用例如503.

In order to inform the browser that the request has not succeeded, you need to pass a http response code that is not 2xx. For your purpose, you could use e.g. 503.

http_response_code(503);

这将确保浏览器理解调用的输出不是成功的(这将由其默认值200来建议).

That will ensure the browser's understanding that the output from the call is not a success (as it would be suggested by the default value of this, i.e. 200).

在该语句之后,如果希望错误消息由PHP层驱动,您仍然可以返回一些JSON.

Following that statement, you can still return some JSON if you want the error messaging to be driven by the PHP layer.

这篇关于Ajax-数据库连接处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆