Backbone は、JSON をデフォルトの応答形式として想定しています。整数を取得すると、バックボーンは数値に対して jquery を使用$.parseJSON()
しており、そうでない場合は有効な JSON として返していると思われます。
複数のエラー メッセージを返したい場合は、それらを配列の個別のフィールドに入れてエンコードし、バックボーンへの応答として送信することをお勧めします。
編集
$.parseJOSN()
バックボーンのソースコードをチェックしただけで、上記の推測とは逆に呼び出されません。
編集2
次の PHP コードがあるとします (フレームワークにとらわれない例を作成したいのですが、それは可能ですが、フレームワークを使用するとより迅速かつスムーズになるため、Slimを選択しました)。
モデルを保存すると、バックボーンは POST メソッドを使用してデータをサーバーに送信します。Slim では、これは次のように変換されます。
$app = new \Slim\Slim();
$app->post('/authors/', function() use($app) {
// We get the request data from backbone in $request
$request = $app->request()->getBody();
// We decode them into a PHP object
$requestData = json_decode($request);
// We put the response object in $response : this will allow us to set the response data like header values, etc
$response = $app->response();
// You do all the awesome stuff here and get an array containing data in $data //
// Sample $data in case of success
$data = array(
'code' => 200,
'status' => 'OK',
'data' => array('id'=>1, 'name' => 'John Doe')
);
// sample $data in case of error
$data = array(
'code' => 500,
'status' => 'Internal Server Error',
'message' => 'We were unable to reach the data server, please try again later'
);
// Then you set the content type
$app->contentType('application/json');
// Don't forget to add the HTTP code, Backbone.js will call "success" only if it has 2xx HTTP code
$app->response()->status( $data['code']);
// And finally send the data
$response->write($data);
私が Slim を使ったのは、それが仕事を終わらせ、すべてが英語のように読めるからです。
ご覧のとおり、Backbone は JSON 形式の応答を必要とします。2xx とは異なる HTTP コードを送信すると、Backbone は実際にはerror
の代わりに を呼び出しますsuccess
。ただし、ブラウザはその HTTP コードもキャッチするので、気をつけてください!
削除された情報
バックボーンparse
関数も JSON を想定しています! 次のコレクションがあるとします。
var AuthorsCollection = Backbone.Collection.extend({
initialize: function( models, options ) {
this.batch = options.batch
},
url: function() {
return '/authors/' + this.batch;
},
// Parse here allows us to play with the response as long as "response" is a JSON object. Otherwise, Backbone will automatically call the "error" function on whatever, say view, is using this collection.
parse: function( response ) {
return response.data;
}
});
parse
レスポンスを検査することはできますが、JSON 以外は受け付けません!