在CodeIgniter中检索JSON POST数据

时间:2022-12-04 16:38:41

I have been trying to retrieve JSON data from my php file.Its giving me a hard time.This is my code

我一直在尝试从我的php文件中检索JSON数据。它让我很难。这是我的代码

Code in my VIEW:

我的视图中的代码:

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',
        });

Trying to retrieve in my Controller:

试图在我的控制器中检索:

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

Outputs Nothing.

输出什么都没有。

Here are my 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!@!@@

My Response which I can See in Developer tools:

我在Developer工具中可以看到的响应:

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

But in browser, the output is nothing. I am trying to solve it for more than 4 hours now but in vain.

但在浏览器中,输出什么都没有。我现在试图解决它超过4个小时但是徒劳无功。

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

My View Code:

我的观点代码:

<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>

Controller Code:

控制器代码:

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

    }

5 个解决方案

#1


0  

General method I use for my Ajax Calls in CI :

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

JS :

JS:

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

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

Controller :

控制器:

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

    //Stuff

    echo json_encode($myobject);
}

#2


9  

I had the exact same problem. CodeIgniter doesn't know how to fetch JSON. I first thought is about the encoding Because I use fetch.js and not jQuery. Whatever I was doing I was getting an notting. $_POST was empty as well as $this->input->post(). Here is how I've solved the problem.

我有同样的问题。 CodeIgniter不知道如何获取JSON。我首先想到的是关于编码因为我使用fetch.js而不是jQuery。无论我做什么,我都会得到一个结论。 $ _POST为空以及$ this-> input-> post()。这就是我解决问题的方法。

Send request (as object prop -- because your js lib might vary):

发送请求(作为对象道具 - 因为你的js lib可能会有所不同):

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.

节点:我将对象类型的数据编码为json。当您设置dataType:'JSON'选项时,jQuery会自行完成此操作。

CodeIgniter (3.1 in my case):

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.

注意:您需要清理$ this-> input-> raw_input_stream。你没有使用$ this-> input-> post(),这意味着CodeIgniter不会自动完成。

As for the response:

至于回应:

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

Alternatively you can do:

或者你可以这样做:

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.

注意:不需要设置标题('Content-Type:application / json'),但我认为这是一个很好的做法。该请求已设置'Accept':'application / json'标头。

So, the trick here is to use $this->input->raw_input_stream and decode your data by yourself.

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

#3


3  

You only have your own answer.

你只有自己的答案。

print_r($_POST);

的print_r($ _ POST);

Return :

回归:

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

Then how will you get : echo $id = $this->input->post('productDetails');

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

You will get id by echo $id = $this->input->post('id');

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

#4


2  

Although OP seems satisfied, choosen answer doesn't tell us the reason and the real solution . (btw that post_array is not an array it's an object indeed ) @jimasun's answer has the right approach. I will just make things clear and add a solution beyond CI.

尽管OP看起来很满意,但选择答案并没有告诉我们原因和真正的解决方案。 (顺便说一下post_array不是一个数组,它确实是一个对象)@jimasun的答案有正确的方法。我会清楚地说明并在CI之外添加一个解决方案。

So the reason of problem is ;

所以问题的原因是;

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

不是CI或PHP,但您的服务器不知道如何处理具有application / json内容类型的请求。所以你没有$ _POST数据。 Php与此无关。阅读更多内容:使用PHP阅读JSON POST

And the solution is ; Either don't send request as application/json or process request body to get post data.

解决方案是;要么不发送请求作为application / json或进程请求体来获取发布数据。

For CI @jimasun's answer is precise way of that.

CI @ jimasun的回答是精确的方式。

And you can also get request body using pure PHP like this.

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

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

#5


2  

I had the same problem but I found the solution.

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

This is the Json that I am sending [{"name":"JOSE ANGEL", "lastname":"Ramirez"}]

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

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

This code was tested and the result is [{"name":"JOSE ANGEL","lastname":"Ramirez"}]

此代码已经过测试,结果为[{“name”:“JOSE ANGEL”,“lastname”:“Ramirez”}]

#1


0  

General method I use for my Ajax Calls in CI :

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

JS :

JS:

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

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

Controller :

控制器:

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

    //Stuff

    echo json_encode($myobject);
}

#2


9  

I had the exact same problem. CodeIgniter doesn't know how to fetch JSON. I first thought is about the encoding Because I use fetch.js and not jQuery. Whatever I was doing I was getting an notting. $_POST was empty as well as $this->input->post(). Here is how I've solved the problem.

我有同样的问题。 CodeIgniter不知道如何获取JSON。我首先想到的是关于编码因为我使用fetch.js而不是jQuery。无论我做什么,我都会得到一个结论。 $ _POST为空以及$ this-> input-> post()。这就是我解决问题的方法。

Send request (as object prop -- because your js lib might vary):

发送请求(作为对象道具 - 因为你的js lib可能会有所不同):

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.

节点:我将对象类型的数据编码为json。当您设置dataType:'JSON'选项时,jQuery会自行完成此操作。

CodeIgniter (3.1 in my case):

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.

注意:您需要清理$ this-> input-> raw_input_stream。你没有使用$ this-> input-> post(),这意味着CodeIgniter不会自动完成。

As for the response:

至于回应:

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

Alternatively you can do:

或者你可以这样做:

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.

注意:不需要设置标题('Content-Type:application / json'),但我认为这是一个很好的做法。该请求已设置'Accept':'application / json'标头。

So, the trick here is to use $this->input->raw_input_stream and decode your data by yourself.

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

#3


3  

You only have your own answer.

你只有自己的答案。

print_r($_POST);

的print_r($ _ POST);

Return :

回归:

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

Then how will you get : echo $id = $this->input->post('productDetails');

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

You will get id by echo $id = $this->input->post('id');

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

#4


2  

Although OP seems satisfied, choosen answer doesn't tell us the reason and the real solution . (btw that post_array is not an array it's an object indeed ) @jimasun's answer has the right approach. I will just make things clear and add a solution beyond CI.

尽管OP看起来很满意,但选择答案并没有告诉我们原因和真正的解决方案。 (顺便说一下post_array不是一个数组,它确实是一个对象)@jimasun的答案有正确的方法。我会清楚地说明并在CI之外添加一个解决方案。

So the reason of problem is ;

所以问题的原因是;

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

不是CI或PHP,但您的服务器不知道如何处理具有application / json内容类型的请求。所以你没有$ _POST数据。 Php与此无关。阅读更多内容:使用PHP阅读JSON POST

And the solution is ; Either don't send request as application/json or process request body to get post data.

解决方案是;要么不发送请求作为application / json或进程请求体来获取发布数据。

For CI @jimasun's answer is precise way of that.

CI @ jimasun的回答是精确的方式。

And you can also get request body using pure PHP like this.

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

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

#5


2  

I had the same problem but I found the solution.

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

This is the Json that I am sending [{"name":"JOSE ANGEL", "lastname":"Ramirez"}]

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

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

This code was tested and the result is [{"name":"JOSE ANGEL","lastname":"Ramirez"}]

此代码已经过测试,结果为[{“name”:“JOSE ANGEL”,“lastname”:“Ramirez”}]