如何在REST中使用PUT功能

时间:2013-01-30 15:38:36

标签: php codeigniter

使用这个git-hub库: http://github.com/philsturgeon/codeigniter-restserver 如何使用PUT功能保存数据?

example: example.com/put/some-data/some-data/...

3 个答案:

答案 0 :(得分:0)

您可以像这样使用它:但请注意PUT不太常用且大多数浏览器都不支持

function somename_put() 
        {  
            $data = array('somedata: '. $this->put('some-data'));  
            $this->response($data);  
        }  

答案 1 :(得分:0)

您可以使用ajax请求执行此操作,例如

(假设使用jQuery)

$.ajax({
    url: '/index.php/my_controller/somedata',
    type: 'PUT',
    success: function(result) {
        console.log(result);
    }
});

答案 2 :(得分:0)

根据这个(链接:https://github.com/philsturgeon/codeigniter-restserver/blob/master/application/libraries/REST_Controller.php#L915),$this->put只有在向它传递一个参数时才会返回(这样就可以了:$username = $this->put('username'))。但是在REST_Controller $this->_put_args中,$params = $this->_put_args受到保护,您将扩展此类并可以像<?php // route: /api/users/123 class Users extends REST_Controller { ... // update a user's data public function user_put() { $params = $this->_put_args; // you need sanitize input here, "db" is a pseudo $username = $db->escape($params['username']); $userpass = $db->escape($params['userpass']); $db->update(array( 'username' => $username, 'userpass' => $userpass ), (int) $params['id']); if (!$db->error) { // suppose right code should be 201 for PUT $this->response('Created', 201); } else { $this->response('Internal Server Error', 500); } } } ?> <script> // Some ajax library Ajax("/api/users/123", { method: "PUT", data: {username:"John", userpass:"new pass"}, onSuccess: function(){ console.log("Success!"); } ... }); </script> 一样访问它。

简而言之(这只是一个例子,你可以根据需要改进它);

{{1}}