从js文件到yii2控制器功能的ajax请求 [英] ajax request from a js file to yii2 controller function
本文介绍了从js文件到yii2控制器功能的ajax请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
function facebookAuth() {
$.ajax({
url: 'index.php?r=account/fbauthorize',
type: 'GET'
});
}
这是我编写的一个简单函数,只是为了调用控制器中的函数,GET 类型可以正常工作,但 POST 不行.给我这个错误错误的请求 (#400):无法验证您提交的数据."
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."
这与yii2中的CSRF验证有关,但我无法解决.
it is something to do with CSRF validation in yii2, but i can't solve it.
推荐答案
有两个重要步骤:
1) 按如下方式注册您的 js 文件:
1) Register your js file as follows:
$this->registerJsFile(Yii::$app->homeUrl . 'js/test.js', [JqueryAsset::className()]);
2) 在 ajax 请求中,您需要随数据一起发布以下值:
2) In ajax request you need to post following value along with data:
yii.getCsrfParam(): yii.getCsrfToken()
CSRF 是一种安全功能,可以在控制器中禁用,但不推荐使用.
CSRF is a security feature which can be disabled in controller, but it is not recommended.
这篇关于从js文件到yii2控制器功能的ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文