Json如何在yii2中编码? [英] how to Json encode in yii2?
问题描述
尝试对json进行编码并在yii2
中接收400: Bad Request
.我正在尝试在Rest客户端中编码,但无法正常工作.
Attempting to encode json and receive 400: Bad Request
in yii2
. I am trying to encode in Rest client but it is not working properly.
<?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);
}
}
?>
错误图片.
错误图片
推荐答案
解决方案1:如果万一控制器的所有操作都将传递json,则还可以考虑扩展
Solution 1: In case if all your controller's actions will deliver json you may also consider extanding yii\rest\Controller instead of 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;
}
}
注意:您也可以使用 ActiveController 扩展了 yii \ rest \ Controller (请参见其余文档).
NOTE: you may also use ActiveController which extends yii\rest\Controller (see rest docs) if you need to handle CRUD operations.
解决方案2::扩展 yii \ web \ Controller 是通过使用 yii \ filters \ ContentNegotiator .请注意,此处$enableCsrfValidation
设置为 false 可能是强制性的,因为其
Solution 2: A different approach when extending yii\web\Controller is by using yii\filters\ContentNegotiator. Note that setting $enableCsrfValidation
to false may be mandatory here as it is explained in its related docs :
是否启用CSRF(跨站请求伪造)验证. 默认为true.启用CSRF验证后,表单将提交到 Yii Web应用程序必须源自同一应用程序. 否则,将引发400 HTTP异常.
Whether to enable CSRF (Cross-Site Request Forgery) validation. Defaults to true. When CSRF validation is enabled, forms submitted to an Yii Web application must be originated from the same application. If not, a 400 HTTP exception will be raised.
注意,此功能要求用户客户端接受cookie.还, 要使用此功能,通过POST方法提交的表单必须包含一个 名称由$ csrfParam指定的隐藏输入.您可以使用 yii \ helpers \ Html :: beginForm()生成他的隐藏输入.
Note, this feature requires that the user client accepts cookie. Also, to use this feature, forms submitted via POST method must contain a hidden input whose name is specified by $csrfParam. You may use yii\helpers\Html::beginForm() to generate his hidden input.
上面的代码可以这样重写:
The above code may be rewritten this way :
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;
}
}
这篇关于Json如何在yii2中编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!