post提交表单的时候出现在这个错误是因为Yii2.0默认开启了_crsf的验证
可以在控制器里局部禁用
public $enableCsrfValidation = false ->覆盖父类的属性
也可以在配置文件中全局禁用
'components' => [
'request' => [
/**
/*!!! insert a secret key in the following (if it is empty) - this is required by
/*cookie validation
/**
'cookieValidationKey' => '83r5HbITBiMfmiYPOZFdL-raVp4O1VV4',
'enableCookieValidation' => false,
'enableCsrfValidation' => false,
]
当然,我们并不建意这样做。
如果是用ActiveForm生成的表单,用传统的POST提交这里是不会有问题的。
我们可以来看看YII2.0的源码。
\yii\widgets\ActiveForm
这个类里面有一个run方法
/**
* Runs the widget.
* This registers the necessary javascript code and renders the form close tag.
* @throws InvalidCallException if `beginField()` and `endField()` calls are not matching
*/
public function run()
{
if (!empty($this->_fields)) {
throw new InvalidCallException('Each beginField() should have a matching endField() call.');
}
$content = ob_get_clean();
echo Html::beginForm($this->action, $this->method, $this->options);
echo $content;
if ($this->enableClientScript) {
$id = $this->options['id'];
$options = Json::htmlEncode($this->getClientOptions());
$attributes = Json::htmlEncode($this->attributes);
$view = $this->getView();
ActiveFormAsset::register($view);
$view->registerJs("jQuery('#$id').yiiActiveForm($attributes, $options);");
}
echo Html::endForm();
}
可以看到 echo Html::beginForm($this->action, $this->method, $this->options);这样一句。
在Html::beginForm()这个方法里面
if ($csrf && $request->enableCsrfValidation && strcasecmp($method, 'post') === 0) {
$hiddenInputs[] = static::hiddenInput($request->csrfParam, $request->getCsrfToken());
}
这样一段代码就是在表单写入了一个hide input加入了_csrf
如果不是用的ActiveForm则需要手动加入:
<input type="hidden" name="<?php echo Yii::$app->request->csrfParam;?>" value="<?php echo Yii::$app->request->getCsrfToken();?>">
如果是ajax post则要在data后面也带上这个参数
YII2.0 标准写法
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<?= Html::csrfMetaTags() ?>
<title><?= Html::encode($this->title) ?></title>
<?php $this->head() ?>
</head>
表单
<?php $form = ActiveForm::begin(['id' => 'login-form']); ?>
<?php ActiveForm::end(); ?>
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。