在Yii2中以JSON格式获取响应 [英] Get response in JSON format in Yii2
问题描述
我正在尝试将响应数组和响应数组转换为JSON格式.我已经尝试过在SO和其他网站(例如 web1 )中发布的所有答案. a>, web2 添加header('Content-Type: application/json')
,然后echo json_encode($data,JSON_PRETTY_PRINT);
但是我总是得到文本格式的输出.
有人可以帮我解决这个问题吗?
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,web2 adding 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.
助手类:
public static function renderJSON($data) {
header('Content-Type: application/json');
echo json_encode($data,JSON_PRETTY_PRINT);
}
我的控制器:
if ($model->login()) {
$user = User::findByUsernameOrEmail($request->post('username'));
$userArray = ArrayHelper::toArray($user);
Helpers::renderJSON($userArray);
我试图打印userArray
,它看起来像这样:
I tried to printing the userArray
and it looks like this:
Array
(
[name] => abc
[lastname] => xyz
[username] => test_test
)
Json输出:(html/text)
Json output: (html/text)
{
"name": "abc",
"lastname": "xyz",
"username": "test_test"
}
推荐答案
设置
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
在return
之前某个位置的控制器动作中.
in the controller's action somewhere before return
.
这篇关于在Yii2中以JSON格式获取响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!