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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?