在 CodeIgniter 中检索 JSON POST 数据

Retrieve JSON POST data in CodeIgniter

我一直在尝试从我的 php file.Its 中检索 JSON 数据,这让我很难 time.This 是我的代码

我视图中的代码:

var productDetails = {'id':ISBNNumber,'qty':finalqty,'price':finalprice,'name':bookTitle};

        var base_url = '<?php echo site_url() ?>';
        $.ajax({
            url: "<?php echo base_url() ?>index.php/user/Add_to_cart/addProductsToCart",
            type: 'POST',
            data:productDetails,
            dataType:'JSON',
        });

正在尝试在我的控制器中检索:

echo $this->input->post("productDetails");

没有输出。

这是我的 headers:

Remote Address:[::1]:80
Request URL:http://localhost/CI/index.php/user/Add_to_cart/addProductsToCart
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8,fr;q=0.6
Connection:keep-alive
Content-Length:52
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Cookie:ci_session=3E5SPro57IrJJkjs2feMNlmMrTqEXrTNN8UyEfleeothNnHwNxuCZDSx4a7cJZGjj7fyr2KLpj%2BPNJeGRSzSPVmcFHVEdhSk4D47ziOl4eZcTUAZlQrWa3EYIeQJVWxMpiGZS26MEfbSXNmfel9e8TcsJTreZHipvfisrJovbXEAW4Uv%2BwrJRep1KCi1MMaDCVJb9UEinRVcDtYe%2F86jhn7kOj4kraVmVzx%2FsOaO0rAxLyAUtez%2Feaa4zBwpN3Td153sAoIb3WxVHoEj2oKyH5prVHigbIhIBR6XZqjBkM6hjBuoD2OSZ2wgLbp9DEENMoqui4WYyHROBuS2DYiJajblcS0KiFga5k%2FQOODvE7p6n%2BozN5ciDliVjJ4PnJ5PD1GaPEmec5%2FbQSlOHYWZk%2F2Blzw3Nw0EtLL7wKDzzQY%3Df645c36bb3548eb8de915b73f8763d97a47783ce
Host:localhost
Origin:http://localhost
Referer:http://localhost/CI/index.php/user/view_available_books/viewAvailableBooks/5
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36
X-Requested-With:XMLHttpRequest
**Form Dataview** sourceview URL encoded
id:234
qty:1
price:0.00
name:dasdadsd2q3e!@!@@

我在开发者工具中看到的回复:

    Array
(
    [id] => 234
    [qty] => 1
    [price] => 0.00
    [name] => dasdadsd2q3e!@!@@
)

但是在浏览器中,输出什么也没有。我现在已经尝试解决了 4 个多小时,但徒劳无功。

print_r($_POST); // outputs nothing
echo $data = file_get_contents('php://input'); //outputs nothing
echo $id    = $this->input->post('productDetails');// outputs nothing

我的查看代码:

<script>
    $('#addtoCart').on('click',function(event){
        event.preventDefault();
        $(this).attr('disabled',"disabled");
        finalprice = $.trim($('#price').val());
        finalqty = $.trim($('#quantity').val());

        var productDetails = JSON.stringify({'id':ISBNNumber,'qty':finalqty,'price':finalprice,'name':bookTitle});

        var base_url = '<?php echo site_url() ?>';
        // console.log($);
        $.ajax({
            url: "<?php echo base_url() ?>index.php/user/Add_to_cart/addProductsToCart",
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            data:productDetails,
            dataType:'html',
        });


    });
</script>

控制器代码:

function addProductsToCart(){
        var_dump(json_decode(file_get_contents("php://input")));
        print_r($_POST);
        // $data = json_decode($_POST["productDetails"]);
        // var_dump($data);
        // echo $data = file_get_contents('php://input');
// print_r(json_decode($data));
        // $id    = $this->input->post('id');
        // $qty   = $this

    }

你只有自己的答案。

print_r($_POST);

Return :

Array
(
    [id] => 234
    [qty] => 1
    [price] => 0.00
    [name] => dasdadsd2q3e!@!@@
)

那你将如何获得:echo $id = $this->input->post('productDetails');

您将通过 echo $id = $this->input->post('id');

获得 id

我在 CI 中用于 Ajax 调用的一般方法 :

JS :

post_array =
{
    "myvar" : "value1",
    "myvar2": "value2"
} 

$.post(baseUrl + "/AjaxController/my_function", post_array,
    function(data)
    {
        var res = jQuery.parseJSON(data);
        alert(res.property);
    }  

控制器:

public function my_function()
{
    $myvar = $this->input->post('myvar');
    $myvar2 = $this->input->post('myvar2'); 

    //Stuff

    echo json_encode($myobject);
}

我遇到了完全相同的问题。 CodeIgniter 不知道如何获取 JSON。我首先想到的是编码,因为我使用 fetch.js 而不是 jQuery。无论我在做什么,我都得到了注意。 $_POST$this->input->post() 一样是空的。这是我解决问题的方法。

发送请求(作为对象道具——因为你的 js 库可能不同):

method: 'POST',
headers: {
  'Accept': 'application/json',
  'Content-Type': 'application/json'
},
body: JSON.stringify({
  ready: 'ready'
})

Node: I encode my data of type object into json. jQuery does this by itself when you set the dataType: 'JSON' option.

CodeIgniter(在我的例子中是 3.1):

$stream_clean = $this->security->xss_clean($this->input->raw_input_stream);
$request = json_decode($stream_clean);
$ready = $request->ready;

Note: You need to clean your $this->input->raw_input_stream. You are not using $this->input->post() which means this is not done automatically by CodeIgniter.

至于回复:

$response = json_encode($request);
header('Content-Type: application/json');
echo $response;

或者你可以这样做:

echo $stream_clean;

Note: It is not required to set the header('Content-Type: application/json') but I think it is a good practice to do so. The request already set the 'Accept': 'application/json' header.

所以,这里的技巧是使用 $this->input->raw_input_stream 并自行解码数据。

尽管OP看起来很满意,但选择的答案并没有告诉我们原因和真正的解决方案。 (顺便说一句 post_array 不是数组,它确实是一个对象)@jimasun 的回答有正确的方法。我只会把事情弄清楚并添加一个超出 CI.

的解决方案

所以问题的原因是;

Not CI or PHP, but your server doesn't know how to handle a request which has an application/json content-type. So you will have no $_POST data. Php has nothing to do with this. Read more at : Reading JSON POST using PHP

解决方案是; 要么不要以 application/json 形式发送请求,要么不要处理请求正文以获取 post 数据。

For CI @jimasun 的回答就是这样。

你也可以像这样使用纯 PHP 来获取请求体。

$json_request_body = file_get_contents('php://input');

我遇到了同样的问题,但我找到了解决方案。

这是我发送的 Json [{"name":"JOSE ANGEL", "lastname":"Ramirez"}]

$data = json_decode(file_get_contents('php://input'), true);
echo json_encode($data);

这段代码已经过测试,结果是[{"name":"JOSE ANGEL","lastname":"Ramirez"}]

我来晚了一点,但我没有在我的申请中找到相同问题的答案。我认为它可以帮助将来像我这样的人。

如果上述解决方案中的 none 对您有效,那么请确保您没有在 post URL 的末尾添加“/”。我在 post 请求 URL.

末尾为这个“/”浪费了 4 个小时 如果您的 URL 以“/”结尾,

CI4 会为 post 请求进行内部重定向。 当它重定向时,它丢失了请求中的 post 数据。