javascript - AngularJS 发布请求未捕获从 PHP 返回的 JSON 数据

标签 javascript php json angularjs

我一直在本地服务器 (XAMPP) 上使用 Angular 的 $http 服务从 PHP 文件发送和请求数据,但最近当我开始在公开托管的网络服务器上执行此操作时遇到了多个问题。第一个问题是 $http.post 一直给我这个错误:

找不到 www.websitepath.com/Object%20Object

显然不是我输入的 URL。我通过使用 $http 服务并仅指定其 POST 类型来修复此问题。我知道脚本正在连接(因为 AngularJS 脚本正在连接 PHP 脚本)并且 PHP 脚本工作得很好(我自己加载它并获得了我想要的字符串)。然而,AngularJS 一直给我这个:

对象{数据:“”,状态:200, header :函数,配置:对象,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 对象作为我的回复:

对象{数据:“”,状态:200, header :函数,配置:对象,statusText:“OK”

为什么数据是空的?!?!如何让 AngularJS 获取 JSON 数据?我返回的方式有问题吗?

最佳答案

从评论中复制:

尝试在 php 中设置 "Content-Type: application/json" header

遗憾的是我不知道这是在修复什么...

任何 Angular 向导都可以解释为什么没有 Content-Type header 的响应主体作为空字符串传递给 $http 成功回调,而不是一个 json 字符串?

关于javascript - AngularJS 发布请求未捕获从 PHP 返回的 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29480427/

相关文章:

php正则表达式读取带有选择字段的选择表单

javascript - JSON Web token (JWT) - 验证客户端

javascript - 加载 JavaScript 后注入(inject) css

javascript - 从 Google 云端硬盘请求文件元数据时缺少 'downloadUrl' 参数

javascript - 如何在 Javascript 中平滑地移动角色(没有 Canvas)

Javascript ROT13 函数只能部分工作

php - 检查是否设置了对象属性 - SimpleXML

php - 扩展 mysqli_result

javascript - Firefox 将输入字段中放置的文本作为 url 加载

javascript - 通过属性获取 JSON 对象