2016-09-26 19 views
1

我正在使用Laravel/PHP爲Ember輸出一些JSON來提取....這裏有幾件事。使用PHP的EmberJS API問題

首先,我的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代碼段工作正常,但第二個沒有。我收到了Ember關於資源類型的各種錯誤。

下一個問題是Ember的頭。現在我正在使用RESTAdapter一切工作,但我應該使用JSONAPIAdapter而不是?當我試圖把它與JSONAPIAdapterJSONAPISerializer工作,我得到這個錯誤

一個或多個以下項必須存在:\「數據\」, \「錯誤\」,\「元

,我能得到這個錯誤消失,但隨後我得到一個未定義的類型或未知的資源錯誤。

+0

顯示第二代碼段的'return'一部分。第二個問題 - jsonapi必須包含'數據'鍵作爲「主數據」http://jsonapi.org/format/#document-top-level – user1156168

+0

我更新了帖子以顯示返回user1156168 ....我在那裏數組,但我認爲我的PHP是錯誤的,我會再次測試,看看我能找到什麼。你認爲我需要一個序列化器嗎?或者在這種情況下會是過度殺毒? – Teejten

回答

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" 
    } 
    }] 
} 
+0

非常好kumkanillam,謝謝你的回答。該格式與JSONAPI完美配合! – Teejten