【问题标题】:Unable to return json response in Yii2 api无法在 Yii2 api 中返回 json 响应
【发布时间】:2020-10-23 06:26:21
【问题描述】:

我正在尝试返回 JSON 响应。

$rec = Yii::$app->hescoMDC->createCommand(/** @lang text */ "SELECT * FROM a_data_catalogue d WHERE d.`METER_ASSET_NO` = '$new_msn' AND d.`DISCARD_TIME` IS NULL")->queryOne();
             
 if($rec['CONS_NO'])
                {

                    
                    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                    return Json::encode([
                        'status' => 'Not OK',
                        'description' => 'New msn is already attached with a customer ' . $rec['CONS_NO'].' MCO can`t be done'
                    ]);
                       
                }

我正在使用postman 来检查响应,但我得到一个empty 窗口。

【问题讨论】:

  • 您应该显示更多代码以提供更多上下文。除此之外,你确定有东西被退回了吗?您是否使用调试器或类似工具逐步完成了此操作?最后,您可以通过设置响应格式然后再次显式编码来对 json 进行双重编码。

标签: json api rest response yii2-advanced-app


【解决方案1】:

首先,当你使用时:

  Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

您不需要使用 Json::encode() 作为回报。只需返回数组

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-12
    • 2017-06-01
    • 2023-01-28
    • 2016-02-11
    • 2017-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多