检查在使用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');之类的内容呢。然后获取角度以检查是否提供了错误消息:

$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请求文件与部分文件分开,使一切都更容易管理。上面的解决方案不起作用,因为HTML数据在到达JSON之前就已经发送了!