使用 AngularJS $http 检查 php 插入是否成功

Check if php insert was successful when using AngularJS $http

我是 AngularJS 的初学者,但我刚刚弄清楚如何使用 $http 服务将 POST 数据传递到 PHP 文件插入到我的数据库。

这是我的 add.php 文件。它显示我的表单并在底部插入代码块:

<h2>Add Car</h2>
<div ng-controller="formCtrl">
    <form method="POST">
        <label>Make:</label>
        <select ng-model="car.make">
            <option>Make 1</option>
            <option>Make 2</option>
            <option>Make 3</option>
        </select>
        <label>Model:</label>
        <input type="text" ng-model="car.model">
        <input type="submit" ng-click="addCar(car)">
    </form>

    <pre>
        {{message}}
    </pre>
</div>


<?php
$data = json_decode(file_get_contents("php://input"));
$make = $data->make;
$model = $data->model;

$con = new PDO('mysql:host=localhost;dbname=mydb', 'user', 'pass');

$stmt = $con->prepare("INSERT INTO cars (model, make) VALUES(?, ?)");
$stmt->bindParam(1, $model);
$stmt->bindParam(2, $make);
$stmt->execute();
?>

这是我的控制器:

app.controller('formCtrl', function ($scope, $http) {

    $scope.addCar = function (car) {

        $http({
            method: 'POST',
            url: 'tools/add.php',
            data: car,
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        })
        .then(function (response) {
           $scope.message = "great!"; 
        });
    }
});

现在有没有办法检查插入是否成功?我知道您可以使用 rowCount() 函数来检查 PHP 端,然后将您的消息设置为错误或成功插入,但我想知道我的 JS 是否有知道是否实际插入了一行。

检查插入是否成功:

if ($stmt->execute()) { 
   // It worked
} else {
   // It didn't
}

为什么不在 PHP 中添加类似 die('Not successful'); 的内容呢?然后获取angular检查是否提供了错误信息:

$http({
    method: 'POST',
    url: 'tools/add.php',
    data: car,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
})
.then(function (response) { 
    if(!response) {
         // Success
         $scope.message = "great!"; 
    } else {
         // Fail
         alert(response);
    }
});

别忘了您也可以在 Angular 中使用 .success().error()

最后一件事!我发现将我的 JSON 请求文件与部分文件分开可以使一切变得更容易和易于管理。上面的解决方案将不起作用,因为在到达 JSON 东西之前发送了 HTML 数据!