Php 如何在codeigniter控制器中接收ajax json数据

Php 如何在codeigniter控制器中接收ajax json数据,php,jquery,ajax,codeigniter,Php,Jquery,Ajax,Codeigniter,在客户端,我有: var postData = { "id" : id, "message" : message }; console.log(postData); $.ajax({ type: "POST", url: "controller/function", data: postData, success: function(){ alert(id + ' ' + message); } }); 这似乎工作正

在客户端,我有:

var postData = {
    "id" : id,
    "message" : message
};

console.log(postData);

$.ajax({
    type: "POST",
    url: "controller/function",
    data: postData, 
    success: function(){
        alert(id + ' ' + message);
    }
});
这似乎工作正常,因为我可以在chrome开发工具中看到正确的post参数。在我的codeigniter控制器中,我尝试过:

echo 'postid' . $_POST['id'].' '.$_POST['message'];

$postData=$this->input->post('id');

var_dump($postData); exit;
我得到:

Message: Undefined index: id
Message: Undefined index: message

boolean(false)
$\u POST
数组为空


我怎样才能解决这个问题?感谢您的帮助

您可以在ajax选项中添加
数据类型:'json'

$.ajax({
       type: "POST",
       url: "controller/function",
       data: postData,
       dataType:'json',
       success: function(){
           alert(id + ' ' + message);
       }
});

您是否将CI配置为使用CSRF保护?如果是,您需要在POST请求中包含CSRF字段和值

$.ajax({
    type: "POST",
    url: "controller/function",
    data: postData, 
    success: function(data){
        alert(data.id + ' ' + data.message);
    }
});

ajax返回数据中的json对象,您忘记在客户端的
$.ajax
函数中添加数据类型:'json'参数

试着添加contentType属性。嗨,伙计们,我尝试了答案,但不起作用。我想添加contentType,但它应该设置为什么。阿里,我应该解码什么?你使用什么ci版本?我使用的是jquery 1.7.2,它在这里工作….
var id=123,message='test',postData={“id”:id,“message”:message};console.log(postData);$。ajax({type:“POST”,url:“test/do_action”,data:postData,success:function(){alert(id+“”+message);}})请为建议的解决方案添加一些解释。