为什么 post 数据完全为空 post 通过 ajax 发送到 CodeIgniter 控制器?
Why is post data completely empty posting to CodeIgniter controller via ajax?
我已经通读了所有关于同一问题的 SO 帖子,并尝试了所有这些帖子。显然我仍然做错了什么。我可以将所有数据注销到控制器。 Post 数据总是完全为空,我不确定为什么。
jquery
function onDeleteThing(myId, callback) {
console.log(myId) // 10
$.ajax({
'type': 'post',
'contentType': 'application/json',
'cache': false,
'data': {'id': myId},
'url': '/my-url/delete',
'dataType': 'json',
'timeout': 50000
}).done(function (response) {
callback(response);
}).fail(function (error) {
// Total fail.
});
}
控制器
public function delete()
{
if ($this->input->is_ajax_request()) {
error_log(print_r($this->input->post(), true)); // returns: Array()
// even using $_POST returns empty array
// here is an example of how I plan to send the post data to my model
if ($this->My_model->delete($this->input->post('data')) {
echo json_encode(array('status' => 'success'));
} else {
echo json_encode(array('status' => 'fail'));
}
}
}
但是,我 运行 遇到的问题是 $this->input->post('data')
在到达我的控制器时是空的。
编辑
我也可以在网络选项卡中看到:
Request Payload
id=10
问题是您向服务器发送了相互矛盾的信息:
ContentType: "application/json"
RequestBody: "id=10" // Not JSON
如果您不需要发送 json,一种解决方案是简单地从您的 $.ajax
调用中删除 contentType
选项,因为 jQuery 会设置它默认为 application/x-www-form-urlencoded; charset=UTF-8
。
如果您确实希望发送 JSON,则您必须自己将其转换为 JSON,因为 jQuery 无法执行此操作。一种解决方案是使用 JSON.stringify
(如果您需要对 IE7 或更低版本的支持,则添加必要的 polyfill)。
$.ajax({
'type': 'post',
'contentType': 'application/json',
'cache': false,
'data': JSON.stringify({'id': myId}),
'url': '/my-url/delete',
'dataType': 'json',
'timeout': 50000
})
我已经通读了所有关于同一问题的 SO 帖子,并尝试了所有这些帖子。显然我仍然做错了什么。我可以将所有数据注销到控制器。 Post 数据总是完全为空,我不确定为什么。
jquery
function onDeleteThing(myId, callback) {
console.log(myId) // 10
$.ajax({
'type': 'post',
'contentType': 'application/json',
'cache': false,
'data': {'id': myId},
'url': '/my-url/delete',
'dataType': 'json',
'timeout': 50000
}).done(function (response) {
callback(response);
}).fail(function (error) {
// Total fail.
});
}
控制器
public function delete()
{
if ($this->input->is_ajax_request()) {
error_log(print_r($this->input->post(), true)); // returns: Array()
// even using $_POST returns empty array
// here is an example of how I plan to send the post data to my model
if ($this->My_model->delete($this->input->post('data')) {
echo json_encode(array('status' => 'success'));
} else {
echo json_encode(array('status' => 'fail'));
}
}
}
但是,我 运行 遇到的问题是 $this->input->post('data')
在到达我的控制器时是空的。
编辑
我也可以在网络选项卡中看到:
Request Payload
id=10
问题是您向服务器发送了相互矛盾的信息:
ContentType: "application/json"
RequestBody: "id=10" // Not JSON
如果您不需要发送 json,一种解决方案是简单地从您的 $.ajax
调用中删除 contentType
选项,因为 jQuery 会设置它默认为 application/x-www-form-urlencoded; charset=UTF-8
。
如果您确实希望发送 JSON,则您必须自己将其转换为 JSON,因为 jQuery 无法执行此操作。一种解决方案是使用 JSON.stringify
(如果您需要对 IE7 或更低版本的支持,则添加必要的 polyfill)。
$.ajax({
'type': 'post',
'contentType': 'application/json',
'cache': false,
'data': JSON.stringify({'id': myId}),
'url': '/my-url/delete',
'dataType': 'json',
'timeout': 50000
})