不必要的“data"对AngularJS查询的响应


Unwanted "data" wrapper in PHP response to AngularJS query

我正在使用$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会照顾它

我应该做些什么来删除不需要的"数据"包装?

而不是使用通用的承诺API(它似乎返回一个对象与内部的一切),使用$http提供的successerror方法:

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.
    });

似乎您希望onStuff只接收反序列化的JSON数据,但这不是API所做的。传递给$http.get(...).then()回调(即onStuff)的对象是一个具有五个属性的响应对象:data, status, headers, configstatusText——这正是您在控制台输出中看到的。data属性具有反序列化的JSON数据,这就是您必须执行$scope.stuff = data.data的原因。

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

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