ajax request from a js file to yii2 controller function

泄露秘密 提交于 2019-12-08 11:56:39

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!