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 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗