Post form 400 error:
Correct practice:
Add this on the head section of your layout:
<?= Html::csrfMetaTags() ?>
---------------------------------
不推荐的做法,以下做法是取消CSRF令牌验证:
Add this in your controller:
public $enableCsrfValidation = false;
Other methods:
It turned out to be a CSRF validation issue, because the form was written by itself, and in the Yii framework, in order to prevent CSRF attacks, the Post's form data was encapsulated with CSRF token validation.
Workaround Close CSRF Validation
Method One, close in a funding file
‘components‘=>array( ‘request‘=>array( // Enable Yii Validate CSRF Token ‘enableCsrfValidation‘ => true, ),),
When using the Yii form to generate a page, if the form is submitted as a post, a hidden field is added to the page, and the hidden field is the CSRF token validation field
When the user submits the form, the field is submitted to the server side, and the Yii framework compares the hidden fields submitted by the client with the Yii_csrf_token values in the cookie submitted by the client.
The same is true by continuing execution, which throws a 400 exception: "The CSRF token could not being verified."
So there is the problem above, if you are writing a form, you can add a hidden token validation field on the View page's form
Method Two, add hidden validation fields to the form
<input name="_csrf" type="hidden" id="_csrf" value="<?= Yii::$app->request->csrfToken ?>">
If you do not want to CSRF validation, modify the true of method one to false so that Yii does not do post form validation processing.
400 errors for Ajax POST:
Ajax post is also used recently when you're watching a movie. So I'm looking for answers online. Finally, inadvertently in YII from find this answer () Yii_csrf_token this thing, because I opened the enablecsrfvalidation ' =>true, so when the request will be added CSRF verification. So the Ajax POST request is not validated.
Workaround: Just add the Yii_csrf_token manually when the request is done!
For example:
Send Ajax $.ajax ({type: "Post", DataType: ' json ', url: "Index.php?r=movie/insertfavorite", data:{' movie_id ': ' <?php echo $_get[' id ']?> ', ' yii_csrf_token ': ' <?php echo ii::app ()->request->csrftoken> '}, Cache:false, Error:function (XMLHttpRequest, Textstatus, Errorthrown) {alert (errorthrown);}, Success:function (data) {var result= Eval ("(" +data+ ")"); Alert (data)});
Resolves a 400 error in the YII submission post form and 400 issues with Ajax post requests