我创建了一个CakePHP应用程序,在设置了routes.php文件后,我可以发送JSON请求,以便将我的应用程序用作API。为了测试,我创建了一个如下函数:
public function api() {
if($this->request->is('post')) {
$data1 = (string)$this->request->data['Model']['data1'];
$data2 = (string)$this->request->data['Model']['data2'];
//logic goes here,it does stuff and $result is the variable where the result of the login is saved
//$data1 and $data2 are used in the logic
$result = 'result';
$this->set('results',$result);
$this->set('_serialize',array('results'));
}
}
我还使用另一个名称创建了完全相同的函数,该名称旨在通过Web表单使用并且可以正常工作。但是,这个代码,在这个函数这里,当我POST数据(我使用Dev HTTP Client chrome扩展)时,它返回$ results变量为空,就像它没有收到我发送的内容:/ 我通过我使用的chrome扩展程序发送如下数据:
data1='stuff1'&data2='stuff2'
它只返回
{
"results":""
}
(虽然相同的代码在没有json的情况下使用时效果很好。)
我错过了什么吗?它似乎做错了吗?请帮帮我一点..
ps:如果您需要更多信息,请告诉我,我会发布。
提前谢谢!
答案 0 :(得分:0)
访问该帖子的正确方法是
$this->request->data['data1'];
验证发送的数据是做什么的:
public function api() {
//if($this->request->is('post')) {
$data1 = (string)$this->request->data['Model']['data1'];
$data2 = (string)$this->request->data['Model']['data2'];
//logic goes here,it does stuff and $result is the variable where the result of the login is saved
//$data1 and $data2 are used in the logic
$result = 'result';
//$this->set('results',$result);
$this->set('results',array('root'=>$this->request);
$this->set('_serialize',array('results'));
//}
}