我使用以下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数据,但仍然会遇到同样的错误。把头发撕掉了!
知道我可能做错了吗?
答案 0 :(得分:0)
$.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");
}
});
试试这个。
答案 1 :(得分:-1)
根据定义,JSON数据必须是双引号,而不是单引号。
如果您使用ajax发送数据,则更容易提供ajax JSON数据,然后自行转换。
下一点是:您是在尝试在JS中使用PHP还是要发送例如:
"<?=$user->id?>"