)]}',
猫の下-プレフィックス付きのJSONデータを生成する私の短い歴史。 しかし、この話はより一般的な質問をよく示していると思います-自分のサーバー応答形式をどのように追加できますか。 Yiiフレームワークでは、これは非常に簡単に行われます。このため、特定の形式の応答を生成するのはどのクラスであるかを構成で記述するだけで十分です。
構成(/path_to_project/config/web.php-セクションコンポーネント→応答→フォーマッター)に新しいタイプの応答-「jsonvp」を追加し、作成するクラスを割り当てます。
<?php // . . . $config = [ // . . . 'components' => [ // . . . 'response' => [ 'formatters' => [ 'jsonvp' => 'app\components\JsonVpResponseFormatter', ], ], ], // . . . ];
yii\web\Response
クラスには
$formatters
プロパティがあり、これは構成に含まれるものによって補完されます。
Yii::$app->response->format = 'jsonvp';
、クラス
app\components\JsonVpResponseFormatter
を使用して、応答をフォーマットします。 フレームワークには、そのようなクラスを記述するためのルールを規制するインターフェイス
yii\web\ResponseFormatterInterface
あるため、このインターフェイスを新しいクラスに適用できます。
<?php namespace app\components; use yii\helpers\Json; use yii\web\Response; use yii\web\ResponseFormatterInterface; class JsonVpResponseFormatter implements ResponseFormatterInterface { /** * Format as Vulnerability Protected JSON. * @param Response $response */ public function format($response) { $response->getHeaders()->set('Content-Type', 'application/json; charset=UTF-8'); if ($response->data !== null) { $response->content = ")]}',\n" . Json::encode($response->data); } } }
機能を確認するだけです。
<?php namespace app\controllers; use Yii; use yii\web\Controller; /** * site/* actions. * @package app\controllers */ class SiteController extends Controller { /** * Test JSON output * @return array */ public function actionJson() { Yii::$app->response->format = 'jsonvp'; return ['123', '456']; } }
通話中
localhost/index.php?r=site/json
localhost/index.php?r=site/json
のブラウザーでは、次の結果が表示されます。
)]}', ["123","456"]
おわりに
この簡単な方法を使用して、独自の応答形式を作成できます。 たとえば、上記のように、- 脆弱性から身を守ることができるプレフィックス付きのJSON。
誰かがこの記事が役立つことを願っています。 頑張って