问题
function facebookAuth() {
$.ajax({
url: 'index.php?r=account/fbauthorize',
type: 'GET'
});
}
it is a simple function i wrote just to invoke the function in the controller, the GET type works fine, but the POST does not. give me this error "Bad Request (#400): Unable to verify your data submission."
it is something to do with CSRF validation in yii2, but i can't solve it.
回答1:
There are two important steps:
1) Register your js file as follows:
$this->registerJsFile(Yii::$app->homeUrl . 'js/test.js', [JqueryAsset::className()]);
2) In ajax request you need to post following value along with data:
yii.getCsrfParam(): yii.getCsrfToken()
CSRF is a security feature which can be disabled in controller, but it is not recommended.
回答2:
add this two line to your code
contentType: "application/json; charset=utf-8",
dataType: "json",
this will be
$.ajax({
url: 'index.php?r=account/fbauthorize',
type: 'GET',
contentType: "application/json; charset=utf-8",
dataType: "json",
});
Enjoy :)
回答3:
Make sure to set the right access method.
public function behaviors()
{
return [
'verbs' => [
'class' => \yii\filters\VerbFilter::className(),
'actions' => [
'fbauthorize' => ['post'],
],
],
];
}
http://www.yiiframework.com/doc-2.0/yii-filters-verbfilter.html
来源:https://stackoverflow.com/questions/23679332/ajax-request-from-a-js-file-to-yii2-controller-function