如何处理作为HTTP Post发送到cakephp应用程序的JSON数据? [英] How do I handle json data sent as an HTTP Post to a cakephp app?
本文介绍了如何处理作为HTTP Post发送到cakephp应用程序的JSON数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我被发送一个HTTP Post,http请求的正文是一个UTF8编码字符串,我如何访问我的cakephp控制器中的数据?看起来$ this-> params只包含以下内容:
{
pass:[],
named:[],
controller:users,
action:checkin,
plugin:null,
url :{
ext:json,
url:users\ / checkin.json
},
form:[ b $ bisAjax:false
}
正在发布的数据看起来像这样:
{
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 'php:// input'))),true);
}
if(!is_null($ jsonData)和$ jsonData!== false){
$ this-> data = $ jsonData;
}
}
这是一个codenippet,建议在核心,请参见 https://trac.cakephp.org/ticket/6125 。也许这是您要找的。 p>
- Bjorn
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 controller? 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
这篇关于如何处理作为HTTP Post发送到cakephp应用程序的JSON数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文