鉴于我的项目,我正在向 yii2 控制器发出 xhr 请求
在我看来,请求的结构是这样的
var xhr = new XMLHttpRequest();
xhr.open('POST', '$urlToController', true);
xhr.setRequestHeader("Content-type","application/json");
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.onreadystatechange = function () {
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log(xhr.responseText);
}
};
// Print on console first
console.log({ id: JSON.stringify($('#grid').yiiGridView('getSelectedRows')), _csrf : csrfToken});
xhr.send({ id: JSON.stringify($('#grid').yiiGridView('getSelectedRows')), _csrf : csrfToken}});
这是我的控制器:
public function actionTargetController() {
if(Yii::$app->request->isAjax) {
Yii::$app->response->format = Response::FORMAT_JSON;
if (Yii::$app->request->isPost) {
$post = Yii::$app->request->post();
return $post; // Print $post
}
}
}
当我尝试发送数据时,xhr.send()
我在 yii2 控制器中什么也没收到,我得到的响应总是“[]”(空数组)
我也试过用 FormData 对象发送数据,但结果是一样的。
我哪里做错了?预先感谢所有帮助
PS:
_csrf 参数也没有通过,所以我在 beforeAction 方法中禁用了 csrf 验证。
更改 mime 类型并更改您发布的数据。
var xhr = new XMLHttpRequest();
xhr.open('POST', '$urlToController', true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); // <------ other mime type
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.onreadystatechange = function () {
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log(xhr.responseText);
}
};
var params = $('#grid').yiiGridView('getSelectedRows')
.map(function (value) { return "selectedRowIds[]=" + value; }).join("&");
xhr.send("_csrf=" + csrfToken + (params ? "&" + params : ""));
现在您可以通过以下方式获取操作中发布的数据:
$post = Yii::$app->request->post('selectedRowIds');
你得到一个整数数组。
您也可以为此使用 jQuery,因为您已经在使用它了。容易得多:
var params = {selectedRowIds: $('#grid').yiiGridView('getSelectedRows'), _csrf : csrfToken};
$.post('$urlToController', params).done(function(data) {
console.log(data);
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句