我能够通过在 URl 中以以下格式传递 ID 来view
和delete
数据:
/apis/view/id.json
用:
public function view($id) {
$api = $this->Api->findById($id);
$this->set(array(
'api' => $api,
'_serialize' => array('api')
));
}
同样,我想实现add
和edit
,我可以在HTTP正文中传递Json格式的数据并将其存储/编辑在数据库中。
我无法遵循此解决方案:带有 JSON 输入的 CakePHP API PUT
我不明白如何使用
$data = $this->request->input('json_decode');
来实现它。
Add 可以简单地按照文档中给出的方式使用,方法是将 .json 附加到它。您发布数据的 URL 将变为 /apis.json
。这将自动访问 add() 方法。
假设您以以下格式传递 json 值电子邮件和密码:{"email":"abc@def.com","password":"123456"}
public function add(){
$data=$this->request->input('json_decode', true ); //$data stores the json
//input. Remember, if you do not add 'true', it will not store in array format.
$data = $this->Api->findByEmailAndPassword($data['email'],$data['password']);
//simple check to see if posted values match values in model "Api".
if($data) {$this->set(array(
'data' => $data,
'_serialize' => array('data')));}
else{ $this->set(array(
'data' => "sorry",
'_serialize' => array('data')));}
}// The last if else is to check if $data is true, ie. if value matches,
// it will send the input values back in JSON response. If the email pass
// is not found, it will return "Sorry" in json format only.
希望能回答你的问题!Put 也非常相似,除了它会检查数据是否存在,如果不存在,它将创建或修改现有数据。如果您有任何其他疑问,请随时询问:)
如链接文档中所述,CakeRequest::input()
读取原始输入数据,并选择性地通过解码函数传递它。
因此,$this->request->input('json_decode')
为您提供解码的 JSON 输入,如果它的格式遵循 Cake 约定,您只需将其传递给Model
保存方法之一即可。
这是一个非常基本(未经测试)的示例:
public function add()
{
if($this->request->is('put'))
{
$data = $this->request->input('json_decode', true);
$api = $this->Api->save($data);
$validationErrors => $this->Api->validationErrors;
$this->set(array
(
'api' => $api,
'validationErrors' => $validationErrors,
'_serialize' => array('api', 'validationErrors')
));
}
}
这将尝试保存数据并返回保存结果以及可能的验证错误。
如果输入数据的格式不遵循 Cake 约定,则必须相应地对其进行转换。