如何在php脚本中使用angularjs $ resource

时间:2016-12-16 22:23:14

标签: php angularjs

我有关于PHP的问题 - AngularJs,所以我有简单的PHP脚本

<?php
require_once '../../dbConnect.php';

$driverId = $_POST['driverId'];

if (isset($_POST['driverId'])) {

        $sql = "delete from drivers where driver_id='$driverId'";

        if ($mysqli->query($sql) === TRUE) {
            echo mysqli_insert_id($mysqli);
        } else {
            echo "Error updating record: " . $mysqli->error;
        }

        $mysqli->close();
}

?>

目前我将数据传递给这样的脚本

return $http({
    method: 'POST',
    url: '/api/drivers/deleteDriver.php',
    data: $.param(driverObject),
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
});

我不喜欢那个代码,在其他Java项目上我用这样的angularjs $ resource服务将params发送到终点

var deleteDriverResouce = $resource('/api/drivers/deleteDriver.php');

function deleteDriver() {
  deleteDriverResouce.save(driverObject);
}

正如您所看到的那样代码更清晰,更易于使用,我想知道我可以使用$ resource服务将对象传递给php脚本吗?

1 个答案:

答案 0 :(得分:0)

所以我找到了解决方案,我将在这里分享,所以也许有人需要它。为了使用AngularJs $ resource服务,您只需要在PHP脚本中进行小的更改,只需添加$object = json_decode(file_get_contents("php://input"), true);就可以访问通过$ resource发送的对象。这是一个有效的PHP脚本示例。

<?php
require_once '../dbConnect.php';
session_start();

$object = json_decode(file_get_contents("php://input"), true);

if (isset($object['email']) && isset($object['password'])) {

    $email = $object['email'];
    $password = $object['password'];
    $query="select * from members where email='$email'";
    $result = $mysqli->query($query) or die($mysqli->error.__LINE__);
    $row = mysqli_fetch_assoc($result);

    if($row) {
        if (password_verify($object['password'], $row['password'])) {
            $_SESSION["id"] = $row['id'];
            echo 'Login Success!';
        } else {
            session_destroy();
            var_dump(http_response_code(400));
        }
    } else {
        session_destroy();
        var_dump(http_response_code(406));
    }

    $mysqli->close();
} else {
    session_destroy();
    var_dump(http_response_code(400));
}
?>

在UI上我有这个简单而简单的代码:

var userLoginObject = {
  email: 'login@email.com',
  password: 'password123'
};

var authenticationResource = $resource('/api/authentication/authenticate.php');

function logIn() {
  authenticationResource.save(userLoginObject );
}

这比使用丑陋

更好更清洁
return $http({
    method: 'POST',
    url: '/api/drivers/authenticate.php',
    data: $.param(userLoginObject),
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
});