【问题标题】:EmberJS API questions using PHP使用 PHP 的 EmberJS API 问题
【发布时间】:2016-09-27 21:04:36
【问题描述】:

我正在使用 Laravel/PHP 输出一些 JSON 以供 Ember 获取....这里有几件事。

首先,我的 PHP 是这样的(有没有其他发送数据的方法)

        return Response::json([
        'articles'  => $articles->toArray()
        ], $statusCode);   

这是我习惯做的。

      foreach($articles as $article) {
         $response['articles'][] = [ 
            'id'    =>  $article->id,
            'body'  =>  $article->body,
            'title' =>  $article->title
        ];
     }

         return Response::json([
        'articles'  => $articles->toArray()
        ], $statusCode);   

第一个 PHP sn-p 工作正常,但第二个不行。我得到了有关 Ember 资源类型的各种错误。

下一个问题是针对 Ember 头的。现在我正在使用RESTAdapter 进行所有工作,但我应该改用JSONAPIAdapter 吗?当我尝试让它与 JSONAPIAdapterJSONAPISerializer 一起工作时,我得到了这个 error

必须存在以下一个或多个键:\"data\", \"错误\",\"元

。我可以让该错误消失,但随后我收到有关未定义类型或未知资源的错误。

【问题讨论】:

  • 显示第二个 sn-p 的 return 部分。第二个问题 - jsonapi 必须包含 data 键作为“主要数据”jsonapi.org/format/#document-top-level
  • 我更新了帖子以显示返回的 user1156168....我在数组中有它,但我认为我的 PHP 错误,我会再次测试,看看我能找到什么。你认为我需要一个序列化程序还是在这种情况下会有点矫枉过正?

标签: php ember.js


【解决方案1】:

使用 JSONAPIAdapter 不是强制性的,但是如果您可以控制 API,那么您可以很好地使用它。 API 响应应遵循格式 (http://jsonapi.org/format/)

单个资源对象的示例格式,

{
  "data": {
    "type": "articles",
    "id": "1",
    "attributes": {
      // ... this article's attributes
    }        
  }
}

多个资源对象的示例格式,

{      
  "data": [{
    "type": "articles",
    "id": "1",
    "attributes": {
      "title": "JSON API paints my bikeshed!"
    }
  }, {
    "type": "articles",
    "id": "2",
    "attributes": {
      "title": "Rails is Omakase"
    }
  }]
}

【讨论】:

  • 非常好的 kumkanillam,谢谢你的回答。该格式与 JSONAPI 完美配合!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-15
  • 1970-01-01
  • 2021-01-09
  • 2011-11-14
  • 1970-01-01
相关资源
最近更新 更多