php 在 CodeIgniter 中检索 JSON POST 数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28602890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:58:17  来源:igfitidea点击:

Retrieve JSON POST data in CodeIgniter

phpjqueryajaxjsoncodeigniter

提问by Abhinav

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:

我的 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:

我可以在开发人员工具中看到的响应:

    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

    }

采纳答案by AdrienXL

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

回答by jimasun

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.jsand not jQuery. Whatever I was doing I was getting an notting. $_POSTwas empty as well as $this->input->post(). Here is how I've solved the problem.

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

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

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

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

Node: I encode my data of type objectinto json. jQuerydoes this by itself when you set the dataType: 'JSON'option.

节点:我将我的类型数据编码objectjson. jQuery当您设置dataType: 'JSON'选项时,它会自行执行此操作。

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 requestalready set the 'Accept': 'application/json'header.

注意:不需要设置,header('Content-Type: application/json')但我认为这样做是一个很好的做法。在request已经设置了'Accept': 'application/json'头。

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

所以,这里的诀窍是自己使用$this->input->raw_input_stream和解码你的数据。

回答by Erdin? ?orbac?

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

回答by JOSE ANGEL RAMIREZ HERNANDEZ

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"}]

回答by Rana Soyab

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

您将通过以下方式获得 id echo $id = $this->input->post('id');