Yii 2 设置控制器接受 json 请求
Yii 2 set up controller to accept json requests
我是 Yii 2 的新手,但这里是:
我想要完成的是设置一个控制器,它只读入发布到它的任何 json 数据。
我对它在 Yii 中的工作方式有点困惑。
到目前为止我已经尝试过设置一个名为 ftest 的控制器,看看我是否可以得到它 returning 一些 json 这似乎有效:
public function actionFTest(){
$request = Yii::$app->request;
Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
$headers = Yii::$app->response->headers;
$headers->add('Content-Type', 'text/json');
$response = Yii::$app->response;
$response->format = \yii\web\Response::FORMAT_JSON;
$response->data = ['message' => 'Evan .. WHERE ARE YOU?'];
//$notificationData = json_decode(file_get_contents("php://input"), true);
//echo var_dump($notificationData);
}
它有点乱,因为我一直在来回输入代码。我知道我通常应该 return 像 $this->render(etc) 这样的东西,但我不确定我需要什么 return 作为视图。
感谢您提供的任何帮助
这可能会有帮助
use Yii;
use yii\web\Response;
public function actionFTest()
{
Yii::$app->response->format = Response::FORMAT_JSON;
}
Then after that just return a simple array like that:
return ['param' => $value];
读这个
http://www.yiiframework.com/doc-2.0/yii-web-response.html#$格式细节
我是 Yii 2 的新手,但这里是:
我想要完成的是设置一个控制器,它只读入发布到它的任何 json 数据。
我对它在 Yii 中的工作方式有点困惑。
到目前为止我已经尝试过设置一个名为 ftest 的控制器,看看我是否可以得到它 returning 一些 json 这似乎有效:
public function actionFTest(){
$request = Yii::$app->request;
Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
$headers = Yii::$app->response->headers;
$headers->add('Content-Type', 'text/json');
$response = Yii::$app->response;
$response->format = \yii\web\Response::FORMAT_JSON;
$response->data = ['message' => 'Evan .. WHERE ARE YOU?'];
//$notificationData = json_decode(file_get_contents("php://input"), true);
//echo var_dump($notificationData);
}
它有点乱,因为我一直在来回输入代码。我知道我通常应该 return 像 $this->render(etc) 这样的东西,但我不确定我需要什么 return 作为视图。
感谢您提供的任何帮助
这可能会有帮助
use Yii;
use yii\web\Response;
public function actionFTest()
{
Yii::$app->response->format = Response::FORMAT_JSON;
}
Then after that just return a simple array like that:
return ['param' => $value];
读这个 http://www.yiiframework.com/doc-2.0/yii-web-response.html#$格式细节