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

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?