【发布时间】:2015-06-11 09:23:06
【问题描述】:
我一直在我的本地服务器 (XAMPP) 上使用 Angular 的 $http 服务从 PHP 文件发送和请求数据,但最近当我开始在我的公开托管的 Web 服务器上执行此操作时遇到了多个问题。第一个问题是 $http.post 一直给我这个错误:
找不到 www.websitepath.com/Object%20Object
显然不是我输入的网址。我通过使用 $http 服务并仅指定其 POST 类型来解决此问题。我知道脚本正在连接(因为 AngularJS 脚本正在到达 PHP 脚本)并且 PHP 脚本工作得非常好(我自己加载它并得到了我想要的字符串)。然而,AngularJS 不断给我这个:
Object {data: "", status: 200, headers: function, config: Object, statusText: "OK"}
尽管 PHP 脚本正在打印 JSON 字符串,但数据似乎为空。我的 AngularJS 脚本和 PHP 脚本的代码如下:
var promise = $http({
method: "post",
url: fetchTable,
data: {
choice: 2
},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
promise.then(function(response) {
$scope.Units = response.data;
$scope.errorMessage = 'Success!';
console.log($scope.Units);
console.log(response);
},function(error) {
$scope.errorMessage = 'There was a problem fetching information';
});
}]);
这是我用来获取数据的 PHP 脚本:
$request = file_get_contents('php://input');
$data = json_decode($request);
$choice = $data->choicePara;
$query = "SELECT unit_id, unitname, unitlink, unitimg, hp, atk, def, rec, upvotes, downvotes, ranking, tier FROM vote_float_v4 ORDER BY ranking ASC";
$result = mysqli_query($dbc, $query);
if (!$query) {
http_response_code(400);
die();
}
else {
$units_array = array();
while ($unit_row = mysqli_fetch_array($result)) {
$unit = new Unit($unit_row); //Create a new unit object based on the information from MySQL
array_push($units_array, $unit);
}
print_r(json_encode($units_array));
}
PHP 正在打印我想要的内容,并且 AngularJS 脚本未指示任何错误,它无法找到 PHP 脚本。实际上,在我的 PHP 语法出现错误之前,AngularJS 会向我返回警告消息。但由于某种原因,我不断收到这个奇怪的 JSON 对象作为我的响应:
Object {data: "", status: 200, headers: function, config: Object, statusText: "OK"}
为什么数据是空的?!?!如何让 AngularJS 获取 JSON 数据?我退货的方式有问题吗?
【问题讨论】:
-
编辑,错误,见下文我不是角度专家,但文档说你应该使用承诺docs.angularjs.org/api/ng/service/$http的
.success回调(不是.then) -
nvm 我看到了关于像你一样调用它的注释。我唯一的另一个猜测是您没有在 php 中设置“Content-Type: application/json”标头?
-
或者可能是 php 输出实际上并没有进入 http 响应。能否展示一下服务器端代码,如何调用 php url?
-
另外,我没有在 php 中看到 $dbc 定义,您是否出于安全考虑将其删除?而且,如果 $query 在发送数据库请求后是虚假的,那么您就是
die()ing。也许你想检查 $result 是否是假的? -
其实,你的第一个猜测(Content-Type: application/json)成功了!!我会记得从现在开始,我不知道这是必要的。非常感谢!!
标签: javascript php json angularjs