[英]how to Json encode in yii2?
嘗試編碼json並在yii2
接收400: Bad Request
。 我試圖在Rest客戶端編碼,但它無法正常工作。
<?php
namespace app\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\TblUserRegistration;
class UserController extends Controller
{
public function actionRegister()
{
$model = new TblUserRegistration();
$username = $_POST['username'];
echo json_encode($username);
}
}
?>
public function actionRegister()
{
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$model = new TblUserRegistration();
return $_POST['username'];
}
我認為400與json_encode無關
谷歌“yii2 csrf”獲取更多信息。
public function actionRegister() { // is not safe Yii::$app->controller->enableCsrfValidation = false; // set response header \\Yii::$app->response->format = \\yii\\web\\Response::FORMAT_JSON; $model = new TblUserRegistration(); $username = $_POST['username']; return $username; }
或者在視圖中添加scrf:form:
<input name="_csrf" type="hidden" id="_csrf" value="<?= Yii::$app->request->csrfToken ?>">
元:
<?= Html::csrfMetaTags() ?>
解決方案1:如果所有控制器的操作都將傳遞json,您也可以考慮使用yii \\ rest \\ Controller而不是yii \\ web \\ Controller:
namespace app\controllers;
use Yii;
class UserController extends \yii\rest\Controller
{
public function actionRegister()
{
$username = Yii::$app->request->post('username');
return $username;
}
}
注意:如果需要處理CRUD操作,也可以使用ActiveController擴展yii \\ rest \\ Controller (請參閱其余文檔 )。
解決方案2:使用yii \\ filters \\ ContentNegotiator擴展yii \\ web \\ Controller時的另一種方法。 請注意,將$enableCsrfValidation
設置$enableCsrfValidation
false可能是必需的,因為它在相關文檔中有解釋:
是否啟用CSRF(跨站點請求偽造)驗證。 默認為true。 啟用CSRF驗證后,提交給Yii Web應用程序的表單必須來自同一應用程序。 如果沒有,將引發400 HTTP異常。
請注意,此功能要求用戶客戶端接受cookie。 此外,要使用此功能,通過POST方法提交的表單必須包含一個隱藏輸入,其名稱由$ csrfParam指定。 您可以使用yii \\ helpers \\ Html :: beginForm()來生成其隱藏的輸入。
上面的代碼可以這樣重寫:
namespace app\controllers;
use Yii;
use yii\web\Controller;
use yii\filters\ContentNegotiator;
use yii\web\Response;
class UserController extends Controller
{
public $enableCsrfValidation = false;
public function behaviors()
{
return [
'contentNegotiator' => [
'class' => ContentNegotiator::className(),
'formats' => [
'application/json' => Response::FORMAT_JSON,
],
'only' => ['register'],
],
];
}
public function actionRegister()
{
$username = Yii::$app->request->post('username');
return $username;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.