php 在 Yii2 中获取 JSON 格式的响应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41675051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get response in JSON format in Yii2
提问by ASN
I'm trying to convert and array of response into JSON format. I have tried all the answers that were posted on SO and other websites like web1,web2adding header('Content-Type: application/json')
and then echo json_encode($data,JSON_PRETTY_PRINT);
But I'm always getting the output in text format.
Can some one help me in solving this.
我正在尝试将响应数组转换为 JSON 格式。我已经尝试了在 SO 和其他网站上发布的所有答案,如web1、web2添加header('Content-Type: application/json')
然后echo json_encode($data,JSON_PRETTY_PRINT);
但我总是以文本格式获得输出。有人可以帮我解决这个问题吗?
Helpers Class:
帮手类:
public static function renderJSON($data) {
header('Content-Type: application/json');
echo json_encode($data,JSON_PRETTY_PRINT);
}
My Controller:
我的控制器:
if ($model->login()) {
$user = User::findByUsernameOrEmail($request->post('username'));
$userArray = ArrayHelper::toArray($user);
Helpers::renderJSON($userArray);
I tried to printing the userArray
and it looks like this:
我试图打印它userArray
,它看起来像这样:
Array
(
[name] => abc
[lastname] => xyz
[username] => test_test
)
Json output: (html/text)
Json 输出:(html/文本)
{
"name": "abc",
"lastname": "xyz",
"username": "test_test"
}
回答by Bizley
Set
放
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
in the controller's action somewhere before return
.
在控制器之前某处的动作中return
。
回答by Andreas Hinderberger
回答by Yasar Arafath
Simply Add this in controller
只需在控制器中添加它
public function beforeAction($action)
{
\Yii::$app->response->format = Response::FORMAT_JSON;
return parent::beforeAction($action);
}
回答by manglide
use yii\helpers\Json;
use yii\web\Response;
Firstly include the 2 lines above at the top of your controller, then in any of your Controller actions, just before the return statements, include the below
首先在您的控制器顶部包含上面的 2 行,然后在您的任何控制器操作中,就在 return 语句之前,包含以下内容
Yii::$app->response->format = Response::FORMAT_JSON;
return Json::encode([
'message' => 'success'
]);
You can build the return array as you deem fit.
您可以根据需要构建返回数组。