且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2021-12-31 02:33:25

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

So i have found solution and i will share it here so maybe someone will need it. In order to use AngularJs $resource service you just need to make small change in PHP script, just add $object = json_decode(file_get_contents("php://input"), true); on that way you can access to object that you sent via $resource. And here is example of one working PHP script.

<?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上,我有以下简单且最少的代码:

And on UI i have this simple and minimal code:

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

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

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

这比使用丑陋的更好和更干净

That's much better and cleaner than using ugly

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