dshmkgq558192365 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:

/apis/view/id.json

using:

public function view($id) {
        $api = $this->Api->findById($id);
        $this->set(array(
            '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.

  • 写回答

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 :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料