2013-09-20 09:23
浏览 89

如何使用PUT在CakePhp Restful API中获取Json输入

I am able to view and delete the data by passing ID in the URl in format of:



public function view($id) {
        $api = $this->Api->findById($id);
            'api' => $api,
            '_serialize' => array('api')

Similarly I want to implement add and edit, where I can pass data in Json format in the HTTP body and store/edit it in the database.

I couldn't follow the this solution: CakePHP API PUT with JSON input

I couldn't understand how to use

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

to achieve it.

图片转代码服务由CSDN问答提供 功能建议

我能够查看删除数据 在URl中传递ID的格式为:



 公共功能视图($ 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'); 


  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

  • doucheng3811 2013-09-20 15:43

    Add can simply be used as given in documentation by appending .json to it. The URL at which you post the data will become /apis.json. This will automatically access the add() method.

    Assuming you pass json values email and password in such format: {"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.

    Hope that answers your question! Put is also very similar, except it will check if the data exists, if it doesn't it will create or else it will modify existing data. If you have any further doubts don't hesitate to ask :)

    解决 无用
    打赏 举报

相关推荐 更多相似问题