php Yii2 ajax 错误请求 (#400)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25054945/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:37:24  来源:igfitidea点击:

Yii2 ajax bad request (#400)

phpajaxrequestyii2

提问by Ruben

When I use this code, I get this error as a response:

当我使用此代码时,我收到此错误作为响应:

Bad Request (#400): Not possible to verify your data

错误请求 (#400):无法验证您的数据

/**
 * Active toggle
 */
$(document).on('click', '[data-toggle-active-menu-items]', function(e){

    e.preventDefault();

    var id = $(this).data('toggle-active-menu-items');

    $.ajax({
        url: 'active',
        type: 'POST',
        data: {'id': id, _csrf: yii.getCsrfToken()}, 
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            if (data.active == 1)
            {
                $('#list-' + id + ' [data-toggle-active-menu-items]').html('<span class="glyphicon glyphicon-eye-open"></span>');
            } else {
                $('#list-' + id + ' [data-toggle-active-menu-items]').html('<span class="glyphicon glyphicon-eye-close"></span>');
            }
        }
    });
});

I tried adding

我尝试添加

_csrf: yii.getCsrfToken()

_csrf: yii.getCsrfToken()

and

contentType: "application/json; charset=utf-8",
dataType: "json",

contentType: "application/json; charset=utf-8",
dataType: "json",

but that's not working

但这不起作用

it does work when I add this to my controller, but that's no good, I don't want to disable csrf validation

当我将它添加到我的控制器时它确实有效,但这不好,我不想禁用 csrf 验证

public $enableCsrfValidation = false;

公共 $enableCsrfValidation = false;

How can I fix this?

我怎样才能解决这个问题?

采纳答案by Ruben

This is my code now, just ignore the csrf token:

这是我现在的代码,只需忽略 csrf 令牌:

$(document).on('click', '[data-toggle-active-menu-items]', function(e){

        e.preventDefault();

        var id = $(this).data('toggle-active-menu-items');

        $.ajax({
            url: 'active',
            type: 'POST',
            data: {'id': id},
            dataType: "json",
            success: function(data) {
                if (data.active == 1)
                {
                    $('#list-' + id + ' [data-toggle-active-menu-items]').html('<span class="glyphicon glyphicon-eye-open"></span>');
                } else {
                    $('#list-' + id + ' [data-toggle-active-menu-items]').html('<span class="glyphicon glyphicon-eye-close"></span>');
                }
            }
        });
    });

回答by Phong ??

You can try this way. It's work!

你可以试试这个方法。这是工作!

var csrfToken = $('meta[name="csrf-token"]').attr("content");
$.ajax({
         url: 'request',
         type: 'post',
         dataType: 'json',
         data: {param1: param1, _csrf : csrfToken},
});

回答by Mirocow

  $.ajax({
    url: '$urlSave',
    type: 'post',
    data: {payload: payload, _csrf: yii.getCsrfToken()},        
    dataType: 'json',
  }).success(function(response) {
  });

other examples: http://docs.mirocow.com/doku.php?id=yii2:docs#добавление_csrftoken_в_ajax_запрос_yii2

其他示例:http: //docs.mirocow.com/doku.php?id=yii2: docs#добавление_csrftoken_в_ajax_запрос_yii2

回答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 Maksim Tikhonov

In my case i've solved this problem with blocking csrf-verification for "site/save-order" route (actionSaveOrder).

就我而言,我通过阻止“站点/保存订单”路由(actionSaveOrder)的 csrf 验证解决了这个问题。

class SiteController extends Controller {
    ...
    public function beforeAction($action) {
        $this->enableCsrfValidation = ($action->id !== "save-order"); // <-- here
        return parent::beforeAction($action);
    }
}

回答by leila

i had the same issue but i noticed that i forgot to add Html::csrfMetaTags()in the head section and that actually fixed it for me best of luck

我有同样的问题,但我注意到我忘记添加Html::csrfMetaTags()头部部分并且实际上为我修复了它祝我好运

回答by eric

Maybe your AJAX header "Content-Type"need to change on "application/x-www-form-urlencoded; charset=UTF-8"

也许您的 AJAX 标头"Content-Type"需要更改"application/x-www-form-urlencoded; charset=UTF-8"