【发布时间】:2016-04-16 10:32:39
【问题描述】:
如何使用 PHP 检索通过 $http.get 请求传递的参数?
这是我的控制器:
app.controller('phonesCtrl', function ($scope, $http, $routeParams) {
$scope.make = $routeParams.make;
console.log($routeParams); // Console displays 'Object {make: "apple"}'
console.log($scope.make); // Console displays 'apple'
$http({
method: 'POST',
url: 'tools/get.php',
params: $routeParams, // Already an object: "{"make" : apple}"
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(function (response) {
$scope.phones = response.data;
});
});
我的 PHP 尝试: 适用于 $http.post,但有些事情告诉我,我不能使用 file_get_contents 函数来做同样的事情。
<?php
$data = json_decode(file_get_contents("php://input"));
var_dump($data); // Outputs NULL
var_dump($_POST["make"]); // Outputs NULL
var_dump($_POST); // Outputs empty array
$con = new PDO('mysql:host=localhost;dbname=mydb', 'root', 'root');
$stmt = $con->prepare("SELECT * FROM phones WHERE make = ?");
$stmt->bindParam(1, $make);
$stmt->execute();
$result = json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
print_r($result);
?>
我还使用$routeProvider 服务来保持我的链接干净。起初我意识到控制台输出的是空白对象,所以我将配置更改为:
.when('/get/:make', { // Added /:make
templateUrl: 'tools/get.php',
controller: 'phonesCtrl'
})
所以现在当我导航到 /get/apple 时,我的控制台会输出“apple”。
【问题讨论】:
-
您可以尝试将 javascript 对象而不是字符串作为 $http 的参数: var make = {make: $routeParams.phone};
-
永远不要尝试手动制作 json ......这很容易出错,让
$http为你做更简单 -
你为什么要问
file_get_contents?我猜 PHP 告诉过你,它需要string(文件名)作为第一个参数,而你传递的是array($_GET)。这没有任何意义。 BTW 顾名思义,函数file_get_contents将第一个参数中的文件名指定的文件内容返回为string。但是你只是发送一个 GET 参数,根本没有文件,你为什么要使用那个函数?您已经在$_GET数组中以字符串形式获取 GET 参数。 -
@DawidFerenczy 我现在只是在玩。起初我有
file_get_contents("php://input"),因为这就是我为我的post请求所做的事情并且它有效。我不确定此时我在做什么。 -
@PatrickKelleter 感谢您指出这一点,我认为这比原来要困难得多。
标签: php angularjs xmlhttprequest