【问题标题】:JQuery ajax call gets 400 bad requestJQuery ajax 调用收到 400 错误请求
【发布时间】:2015-12-01 04:40:05
【问题描述】:

我正在使用下面的 JS 代码来发送一个 ajax 请求:

var data = JSON.stringify({
            'user_id': '<?=$user->id?>',
            'package_id': '<?=$bundle->package_id?>',
            'YII_CSRF_TOKEN': '<?=Yii::app()->request->csrfToken?>'
        });

        $.ajax({
            url: "/bundle/ajaxRemove",
            data: data,
            type: "POST",
            contentType: "application/json",
            dataType: "json",
            error: function (xhRequest, ErrorText, thrownError) {
                alert("Failed to process user correctly, please try again");
                console.log('xhRequest: ' + JSON.stringify(xhRequest) + "\n");
                console.log('ErrorText: ' + ErrorText + "\n");
                console.log('thrownError: ' + thrownError + "\n");
            }

        }).done(function (msg) {
            console.log(msg);
        });

问题是,每当我提交此代码时,服务器都会不断返回 400 Bad Request Error 消息。

我尝试以 post 数据而不是 json 数据的形式提交,但仍然收到相同的错误。在这里扯我的头发!

知道我做错了什么吗?

【问题讨论】:

  • 那么你的服务器端代码在哪里?您在服务器端进行了哪些调试以了解返回 400 的原因?

标签: jquery ajax yii


【解决方案1】:
 $.ajax({
                    dataType: 'json',
                    type: 'POST',
                    contentType: false,
                    data: {
                        user_id: '<?=$user->id?>',
                        package_id: '<?=$bundle->package_id?>',
                        YII_CSRF_TOKEN:'<?=Yii::app()->request->csrfToken?>'},
                    url: '<?php echo Url::to(["/bundle/ajaxRemove"]); ?>',

                    success: function(data) {


                    },
                    error: function (xhRequest, ErrorText, thrownError) {
                    alert("Failed to process user correctly, please try again");
                    console.log('xhRequest: ' + JSON.stringify(xhRequest) + "\n");
                    console.log('ErrorText: ' + ErrorText + "\n");
                    console.log('thrownError: ' + thrownError + "\n");
                    }
                });

试试这个。

【讨论】:

    【解决方案2】:

    根据定义,JSON 数据必须使用双引号,而不是单引号。

    如果你是使用ajax发送数据,那么给ajax JSON数据,然后自己转换就容易多了。

    下一点是:你是想在你的 JS 中使用 PHP 还是你想发送例如:

    "<?=$user->id?>"
    

    【讨论】:

    • JSON.stringify 生成的 JSON 会有双引号。那里发生的事情是他正在传递一个用于序列化的 js 对象文字。那里没问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-03
    • 2015-06-12
    • 2020-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多