Solve yii2 ajax post submission error Bad Request (#400)---Unable to verify your data submission scheme

Solve yii2 ajax post submission error Bad Request #400--Unable to verify your data submission scheme

Cause Analysis

It is because of the anti-csrf problem of yii2.0, the submission is unsuccessful without csrftoken

The first solution is to turn off Csrf

Closed inside the controller

public $enableCsrfValidation = false;

or

public function init(){
    
    
     $this->enableCsrfValidation = false;
}

The second solution is to add hidden fields in the form

You can add a csrftoken hidden domain yourself and pass it to the controller along with other data.

 <input type="hidden" name="_csrf" id="_csrf" value="<?= Yii::$app->request->getCsrfToken() ?>">

Passing the value of name as _csrf here is the key point. I first passed name=_csrf. If it is not successful, then find the reason. It turns out that the token name here must be the same as the parameter defined in the configuration file in your framework. The names are the same. main.php configuration file

Insert picture description here

The third solution is to add the _csrf field in AJAX

var csrfToken = $('meta[name="csrf-token"]').attr("content");

$.ajax({

type: 'POST',

url: url,

data: {_csrf:csrfToken},

success: success,

dataType: dataType

});

Guess you like

Origin blog.csdn.net/guo_qiangqiang/article/details/112977744