jQuery 使用 Yii 2 在 Ajax 调用上收到错误请求(#400)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27126050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting bad request (#400) on Ajax calls using Yii 2
提问by Kartz
This is my code:
这是我的代码:
$(document).on('change', '#tblhotel-int_zone_id', function(e){
var zoneId = $(this).val();
var form_data = {
zone: zoneId
};
$.ajax({
url: "state",
type: "POST",
data: form_data,
success: function(response)
{
alert(response);
}
});
});
This shows:
由此可见:
Bad Request (#400): Unable to verify your data submission.
错误请求 (#400):无法验证您提交的数据。
And I already have <?= Html::csrfMetaTags() ?>
. How can I fix this problem?
我已经有了<?= Html::csrfMetaTags() ?>
。我该如何解决这个问题?
回答by Mihai P.
Note: See the answer from Skullcrasherto fix the issue in the correct way as my answer suggests disabling the Cross-Site Request Forgery.
注意:请参阅Skullcrasher 的答案以正确方式解决问题,因为我的答案建议禁用Cross-Site Request Forgery。
You have a problem with enableCsrfValidation. To read more about it you can read here.
您的 enableCsrfValidation 有问题。要阅读有关它的更多信息,您可以在这里阅读。
To disable CSRF, add this code to your controller:
要禁用 CSRF,请将此代码添加到您的控制器:
public function beforeAction($action) {
$this->enableCsrfValidation = false;
return parent::beforeAction($action);
}
This will disable for all actions. You should probably, depending on the $action, disable it only for specific actions.
这将禁用所有操作。您可能应该根据 $action 仅对特定操作禁用它。
回答by Faenor
As the answer from Mihai P. states, your problem is CSRF validation. It is also true that you could disable the validation for your actions, but this is not considered a good solution.
正如 Mihai P. 的回答所述,您的问题是 CSRF 验证。您也可以禁用对您的操作的验证,但这并不是一个好的解决方案。
As you have a problem in your Ajax request with the validation, you could also use a Yii JavaScript function to add the CSRF token to your formdata that you send in the Ajax request.
由于您的 Ajax 请求在验证时遇到问题,您还可以使用 Yii JavaScript 函数将 CSRF 令牌添加到您在 Ajax 请求中发送的表单数据中。
Just try to add the token to your form data as follows:
只需尝试将令牌添加到您的表单数据中,如下所示:
var form_data = {
zone: zoneId,
_csrf: yii.getCsrfToken()
};
I hope this helps and you therefore don't have to disable CSRF validation.
我希望这会有所帮助,因此您不必禁用 CSRF 验证。
In addition to manually add the CSRF token you can check if there is an X-CSRF header set in the request.
除了手动添加 CSRF 令牌之外,您还可以检查请求中是否设置了 X-CSRF 标头。
回答by Oleg
Add this code at the bottom of your layout:
在布局底部添加此代码:
<script>
$.ajaxSetup({
data: <?= \yii\helpers\Json::encode([
\yii::$app->request->csrfParam => \yii::$app->request->csrfToken,
]) ?>
});
</script>
回答by Ng? V?n Thao
Use:
用:
var csrfToken = $('meta[name="csrf-token"]').attr("content");
$.ajax({
url: 'request',
type: 'post',
dataType: 'json',
data: {param1: param1, _csrf : csrfToken},
});
More detail: Yii2: Using csrf token
更多细节:Yii2:使用 csrf 令牌
回答by H?n ?m
You need to disable CSRF validation in the before actionfunction:
您需要在before action函数中禁用 CSRF 验证:
public function beforeAction($action) {
if($action->id == "action name need to disable")
$this->enableCsrfValidation = false;
return parent::beforeAction($action);
}
Or using the GET method.
或者使用GET 方法。
回答by Prescol
This works. Change the csrfParam with your own in Config/main.php
这有效。在 Config/main.php 中使用您自己的更改 csrfParam
'components' => [
'request'=>[
'csrfParam'=>"othername"
],
...
Remember that you must include in your requests the token with the same name as you defined in config.
请记住,您必须在请求中包含与您在 config.xml 中定义的名称相同的令牌。
回答by Алексей
/backend/config/main-local.php
/backend/config/main-local.php
'components' => [
'request' => [
'cookieValidationKey' => 'unique code',
'csrfCookie' => ['httpOnly' => true, 'path' => '/admin/'],
],
],
/frontend/config/main-local.php
/frontend/config/main-local.php
'components' => [
'request' => [
'cookieValidationKey' => 'unique code',
'csrfCookie' => ['httpOnly' => true, 'path' => '/'],
],
],
回答by Muhammad Omer Aslam
Although it is an old post with alot of answers but there is something missing from all the answers posted, all of them addressed the correct point but when calling the ajax POST
request along with your data you should use the yii.js
functions provided
虽然这是一篇有很多答案的旧帖子,但发布的所有答案中都遗漏了一些内容,所有这些都解决了正确的问题,但是在调用 ajaxPOST
请求和您的数据时,您应该使用yii.js
提供的功能
yii.getCsrfParam()
to get the parameter name of the tokenyii.getCsrfToken()
to get the token or actual value of the csrf-token
yii.getCsrfParam()
获取令牌的参数名称yii.getCsrfToken()
获取 csrf-token 的令牌或实际值
As if you have different param name for front-end defined inside the config.php
or web.php
under the request
components configurations
就好像您在组件配置内部config.php
或web.php
之下定义了不同的前端参数名称request
components=>[
.......
.......
'request' => [
'csrfParam' => '_csrf-frontend',
],
.......
.......
]
then you need to get that name dynamically and the above function help you out.
那么您需要动态获取该名称,上面的函数可以帮助您。
You should
你应该
var form_data = {
zone: zoneId
};
form_data[yii.getCsrfParam()]=yii.getCsrfToken();