post提交表单的时候出现在这个错误是因为Yii2.0默认开启了_crsf的验证

可以在控制器里局部禁用public$enableCsrfValidation=false->覆盖父类的属性也可以在配置文件中全局禁用'components'=>['request'=>[/**/*!!!insertasecretkeyinthefollowing(ifitisempty)-thisisrequiredby/*cookievalidation/**'cookieValidationKey'=>'83r5HbITBiMfmiYPOZFdL-raVp4O1VV4','enableCookieValidation'=>false,'enableCsrfValidation'=>false,]

当然,我们并不建意这样做。

如果是用ActiveForm生成的表单,用传统的POST提交这里是不会有问题的。

我们可以来看看YII2.0的源码。

\yii\widgets\ActiveForm这个类里面有一个run方法/***Runsthewidget.*Thisregistersthenecessaryjavascriptcodeandrenderstheformclosetag.*@throwsInvalidCallExceptionif`beginField()`and`endField()`callsarenotmatching*/publicfunctionrun(){if(!empty($this->_fields)){thrownewInvalidCallException('EachbeginField()shouldhaveamatchingendField()call.');}$content=ob_get_clean();echoHtml::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);");}echoHtml::endForm();}可以看到echoHtml::beginForm($this->action,$this->method,$this->options);这样一句。在Html::beginForm()这个方法里面if($csrf&&$request->enableCsrfValidation&&strcasecmp($method,'post')===0){$hiddenInputs[]=static::hiddenInput($request->csrfParam,$request->getCsrfToken());}这样一段代码就是在表单写入了一个hideinput加入了_csrf如果不是用的ActiveForm则需要手动加入:<inputtype="hidden"name="<?phpechoYii::$app->request->csrfParam;?>"value="<?phpechoYii::$app->request->getCsrfToken();?>">

如果是ajax post则要在data后面也带上这个参数

YII2.0 标准写法

<?php$this->beginPage()?><!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"/><?=Html::csrfMetaTags()?><title><?=Html::encode($this->title)?></title><?php$this->head()?></head>表单<?php$form=ActiveForm::begin(['id'=>'login-form']);?><?phpActiveForm::end();?>