PHP中对AngularJS查询的响应中不需要的“数据”包装器

时间:2014-07-03 18:37:05

标签: php json angularjs http-headers

我使用$http.get

向AngularJS查询某个服务器
var onStuff = function(data) {
  console.log( "Stuff received: " + angular.toJson(data));
  $scope.stuff = data.data;
};

$http.get("https://some.server.net/stuff")
  .then(onStuff, onError);

我的后端是用PHP编写的,并返回格式正确的JSON 我检查了在浏览器中加载https://some.server.net/stuff并通过命令行测试" php stuff.php" 。它看起来像(截断...以适合此屏幕):

[{"id":"1","user_id":"1","name":"Name1"},
 {"id":"2","user_id":"1","name":"Name2"},
 ...
]

请注意这些数据是"解开"或者"只是阵列"
但是,当调用onStuff()时,我的数组被"包裹"在另一个data对象中

这是控制台输出

    Stuff received: 
    {"data":[{"id":"1","user_id":"1","name":"Name1"},
             {"id":"2","user_id":"1","name":"Name2"},...],
     "status":200,
     "config":{"method":"GET",
               "transformRequest":[null],
               "transformResponse":[null],
               "url":"https://some.server.net/stuff",
               "headers":{"Accept":"application/json, text/plain, */*"}},
     "statusText":"OK"} 

这是php的东西

<?
header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");

require_once("stuff.class.php");

$mysqli = new mysqli( "localhost", "user", "password", "database");
$list = Stuff::getList( $mysqli);
echo json_encode( $list);
$mysqli->close();
 ?>

我一直在使用github api教程,JSON响应直接在data中提供 我很确定这与HTTP标头有关,但我希望content-type能够处理它。
我该怎么做才能删除不需要的数据&#34;包装器?

2 个答案:

答案 0 :(得分:1)

不使用通用promise API(似乎返回包含所有内容的对象),而是使用success提供的error$http方法:

var onStuff = function(data) {
  console.log( "Stuff received: " + angular.toJson(data));
  $scope.stuff = data.data;
};

$http.get("https://some.server.net/stuff")
  .success(onStuff).error(onError);

那应该以您期望的格式提供数据。完整的API如下:

  $http({method: 'GET', url: '/someUrl'}).
    success(function(data, status, headers, config) {
      // this callback will be called asynchronously
      // when the response is available
    }).
    error(function(data, status, headers, config) {
      // called asynchronously if an error occurs
      // or server returns response with an error status.
    });

答案 1 :(得分:0)

您似乎希望onStuff仅接收反序列化的JSON数据,但这不是what the API does。传递给$http.get(...).then()回调的对象(即onStuff)是一个响应对象,其中包含五个属性:datastatusheadersconfigstatusText - 这正是您在控制台输出中看到的内容。 data属性具有反序列化的JSON数据,这就是您必须执行$scope.stuff = data.data的原因。

如果您希望onStuff仅接收反序列化的JSON数据,则必须通过中间人调用它:

$http.get("https://example.com/stuff")
  .then( function(response) {
           onStuff(response.data);
         } );