簡體   English   中英

Yii2:如何使用$ dataprovider返回JSON

[英]Yii2: how to return JSON using $dataprovider

我有這個代碼

public function actionIndex() {
    $searchModel = new DraftSearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);


    return $this->render('index', [

                'dataProvider' => $dataProvider,
    ]);
}

我想以JSON格式返回$ dataprovider,請在Yii2中進行此操作的任何想法,謝謝

似乎您需要\\Yii::$app->response->format = \\yii\\web\\Response::FORMAT_JSON

如果您需要json中的返回值,則應使用

public function actionIndex()
{

    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    $searchModel = new DraftSearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    return $dataProvider;
}

或者,如果您需要在渲染中使用dataProvider,則可以嘗試json_encode

public function actionIndex() {
    $searchModel = new DraftSearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

    $myJsonDataProvider  json_encode($dataProvider);

    return $this->render('index', [

                'dataProvider' => $myJsonDataProvider,
    ]);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM