开发者

How do I handle json data sent as an HTTP Post to a cakephp app?

开发者 https://www.devze.com 2022-12-12 13:49 出处:网络
If I\'m being sent an HTTP Post where the body of the http request is just a UTF8 encoded string, how do I access that data in my cakephp co开发者_如何学编程ntroller? It appears that $this->params onl

If I'm being sent an HTTP Post where the body of the http request is just a UTF8 encoded string, how do I access that data in my cakephp co开发者_如何学编程ntroller? It appears that $this->params only contains the following:

{
    "pass":[],
    "named":[],
    "controller":"users",
    "action":"checkin",
    "plugin":null,
    "url":{
        "ext":"json",
        "url":"users\/checkin.json"
    },
    "form":[],
    "isAjax":false
}

The data being posted looks something like this:

{
    "sessionkey":"somecrazykey",
    "longitude":"-111.12345",
    "latitude":"33.12345",
    "reqtype":"checkin",
    "location":"the mall",
    "public":"true"
}


if($this->RequestHandler->requestedWith('json')) {
    if(function_exists('json_decode')) {
        $jsonData = json_decode(utf8_encode(trim(file_get_contents('php://input'))), true);
    }

    if(!is_null($jsonData) and $jsonData !== false) {
        $this->data = $jsonData;
    }
}

This is a codesnippet which was proposed to be in the core, see https://trac.cakephp.org/ticket/6125. Maybe it's what you're looking for.

-- Bjorn


You can use these simplest way :

$data = $this->request->input ( 'json_decode', true) ;
0

精彩评论

暂无评论...
验证码 换一张
取 消