Вопрос

Когда я использую этот код, я получаю эту ошибку как ответ:

плохой запрос (# 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>');
            }
        }
    });
});
.

Я пытался добавить

_csrf: yii.getcsrftoken ()

и

ContentType: «Приложение / JSON; Charset= UTF-8»,

DataType: «JSON»,

Но это не работает

Это делает работу, когда добавляю это на мой контроллер, но это не хорошо, я не хочу отключить проверку CSRF

Публичное $ Enablecsrfvalidation= false;

Как я могу это исправить?

Это было полезно?

Решение 4

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

$(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>');
                }
            }
        });
    });

Другие советы

Вы можете попробовать так.Это работа!

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

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

Другие примеры: http://docs.mirocow.com/doku.php?id=yii2:docs#dobalenie_csrftoken_v_ajax_zapros_yii2

Добавить этот код в нижней части макета:

<script>
    $.ajaxSetup({
        data: <?= \yii\helpers\Json::encode([
            \yii::$app->request->csrfParam => \yii::$app->request->csrfToken,
        ]) ?>
    });
</script>
.

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

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

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

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top