如何在 yii 中获取 json 格式(application/json)的响应?

发布于 2024-09-02 02:11:56 字数 48 浏览 2 评论 0原文

如何在 yii 中获取 json 格式(application/json)的响应?

How to get response as json format(application/json) in yii?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

弱骨蛰伏 2024-09-09 02:11:56

对于 Yii 1:

在您的(基础)控制器中创建此函数:

/**
 * Return data to browser as JSON and end application.
 * @param array $data
 */
protected function renderJSON($data)
{
    header('Content-type: application/json');
    echo CJSON::encode($data);

    foreach (Yii::app()->log->routes as $route) {
        if($route instanceof CWebLogRoute) {
            $route->enabled = false; // disable any weblogroutes
        }
    }
    Yii::app()->end();
}

然后只需在操作结束时调用:

$this->renderJSON($yourData);

对于 Yii 2:

Yii 2 内置了此功能,在控制器操作末尾使用以下代码:

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

For Yii 1:

Create this function in your (base) Controller:

/**
 * Return data to browser as JSON and end application.
 * @param array $data
 */
protected function renderJSON($data)
{
    header('Content-type: application/json');
    echo CJSON::encode($data);

    foreach (Yii::app()->log->routes as $route) {
        if($route instanceof CWebLogRoute) {
            $route->enabled = false; // disable any weblogroutes
        }
    }
    Yii::app()->end();
}

Then simply call at the end of your action:

$this->renderJSON($yourData);

For Yii 2:

Yii 2 has this functionality built-in, use the following code at the end of your controller action:

Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return $data;
薄荷→糖丶微凉 2024-09-09 02:11:56

对于控制器内的 Yii2:

public function actionSomeAjax() {
    $returnData = ['someData' => 'I am data', 'someAnotherData' => 'I am another data'];

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

    return $response;
}

For Yii2 inside a controller:

public function actionSomeAjax() {
    $returnData = ['someData' => 'I am data', 'someAnotherData' => 'I am another data'];

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

    return $response;
}
沧桑㈠ 2024-09-09 02:11:56
$this->layout=false;
header('Content-type: application/json');
echo CJavaScript::jsonEncode($arr);
Yii::app()->end(); 
$this->layout=false;
header('Content-type: application/json');
echo CJavaScript::jsonEncode($arr);
Yii::app()->end(); 
梦在深巷 2024-09-09 02:11:56
$this->layout=false;
header('Content-type: application/json');
echo json_encode($arr);
Yii::app()->end(); 
$this->layout=false;
header('Content-type: application/json');
echo json_encode($arr);
Yii::app()->end(); 
揪着可爱 2024-09-09 02:11:56
class JsonController extends CController {

    protected $jsonData;

    protected function beforeAction($action) {
        ob_clean(); // clear output buffer to avoid rendering anything else
        header('Content-type: application/json'); // set content type header as json
        return parent::beforeAction($action);
    }

    protected function afterAction($action) {
        parent::afterAction($action);
        exit(json_encode($this->jsonData)); // exit with rendering json data
    }

}

class ApiController extends JsonController {

    public function actionIndex() {
        $this->jsonData = array('test');
    }

}
class JsonController extends CController {

    protected $jsonData;

    protected function beforeAction($action) {
        ob_clean(); // clear output buffer to avoid rendering anything else
        header('Content-type: application/json'); // set content type header as json
        return parent::beforeAction($action);
    }

    protected function afterAction($action) {
        parent::afterAction($action);
        exit(json_encode($this->jsonData)); // exit with rendering json data
    }

}

class ApiController extends JsonController {

    public function actionIndex() {
        $this->jsonData = array('test');
    }

}
幻梦 2024-09-09 02:11:56

使用

echo CJSON::encode($result);

示例代码的一种更简单的方法:

public function actionSearch(){
    if (Yii::app()->request->isAjaxRequest && isset($_POST['term'])) {
            $models = Model::model()->searchNames($_POST['term']);
            $result = array();
            foreach($models as $m){
                $result[] = array(
                        'name' => $m->name,
                        'id' => $m->id,
                );


            }
            echo CJSON::encode($result);
        }
}

干杯:)

one more simple way by using

echo CJSON::encode($result);

example code:

public function actionSearch(){
    if (Yii::app()->request->isAjaxRequest && isset($_POST['term'])) {
            $models = Model::model()->searchNames($_POST['term']);
            $result = array();
            foreach($models as $m){
                $result[] = array(
                        'name' => $m->name,
                        'id' => $m->id,
                );


            }
            echo CJSON::encode($result);
        }
}

cheers :)

离鸿 2024-09-09 02:11:56

对于 Yii2 使用这个简单易记的选项

Yii::$app->response->format = "json";
return $data

for Yii2 use this simple to remember option

Yii::$app->response->format = "json";
return $data
旧城空念 2024-09-09 02:11:56

在要渲染 JSON 数据的控制器操作中,例如:actionJson()

public function actionJson(){
    $this->layout=false;
    header('Content-type: application/json');
    echo CJSON::encode($data);
    Yii::app()->end(); // equal to die() or exit() function
}

请参阅更多 Yii API

In the controller action that you want to render JSON data, e.g: actionJson()

public function actionJson(){
    $this->layout=false;
    header('Content-type: application/json');
    echo CJSON::encode($data);
    Yii::app()->end(); // equal to die() or exit() function
}

See more Yii API

终止放荡 2024-09-09 02:11:56
Yii::app()->end()

我认为这个解决方案不是结束应用程序流程的最佳方式,因为它使用了 PHP 的 exit() 函数,这意味着立即退出执行流程。是的,有 Yii 的 onEndRequest 处理程序和 PHP 的 register_shutdown_function 但它仍然太宿命论了。

对我来说,更好的方法是这样

public function run($actionID) 
{
    try
    {
        return parent::run($actionID);
    }
    catch(FinishOutputException $e)
    {
        return;
    }
}

public function actionHello()
{
    $this->layout=false;
    header('Content-type: application/json');
    echo CJavaScript::jsonEncode($arr);
    throw new FinishOutputException;
}

,因此,应用程序流程即使在之后仍然继续执行。

Yii::app()->end()

I think this solution is not the best way to end application flow, because it uses PHP's exit() function, witch means immediate exit from execution flow. Yes, there is Yii's onEndRequest handler, and PHP's register_shutdown_function but it still remains too fatalistic.

For me the better way is this

public function run($actionID) 
{
    try
    {
        return parent::run($actionID);
    }
    catch(FinishOutputException $e)
    {
        return;
    }
}

public function actionHello()
{
    $this->layout=false;
    header('Content-type: application/json');
    echo CJavaScript::jsonEncode($arr);
    throw new FinishOutputException;
}

So, the application flow continues to execute even after.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文