无法在服务器端找到ajax json数据

时间:2013-08-14 21:34:17

标签: php jquery ajax codeigniter

我正在尝试将客户端的jquery中的一些数据发送到codeigniter控制器。我有:

var data = {
    "value" : value,
    "message" : message
};

console.log(postData);

$.ajax({
    type: "POST",
    url: "my_controller/my_function",
    data: data, 
    dataType:'json',
    success: function(){

    }
});

这似乎工作正常,因为我可以在chrome dev工具中看到正确的帖子参数。在我的codeigniter控制器中,我尝试过:

echo 'post' . $_POST['value'].' '.$_POST['message'];

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

var_dump($postData); exit;

我得到了:

Message: Undefined index: value
Message: Undefined index: message

boolean(false)

$_POST数组为空。

我该如何解决这个问题?谢谢你的帮助

2 个答案:

答案 0 :(得分:1)

根据您的代码,我得到了这个效果很好:

JS:

var data = {
    value : '_value_',
    message : '_message_'
};

$.ajax({
    type: "POST",
    url: "php.php",
    data: data, 
    dataType:'json',
    success: function(postData){
        console.log(postData);
    }
});

并在php文件php.php中:

<?php

echo json_encode($_POST);

?>

结果我在浏览器的控制台中得到了这个:

对象{值:“”,消息:“消息”}

答案 1 :(得分:0)

您只需按照代码

即可
var data = {
    value : value,
    message : message
};    

$.ajax({
    type: "POST",
    url: '<?php echo base_url(); ?>my_controller/my_function',
    data: data, 
    dataType:'json',
    success: function(responseFromServer){
        console.log(responseFromServer);
    }
});

在控制器操作方法中,您可以找到这些值,只需使用此代码

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

在返回任何东西之前,只需使用这些代码

 header('Content-Type: application/json', true);
 echo json_encode($postData); 

现在,您在客户端找到了一个Object数组。