ncr*_*fer 8 php rest codeigniter
我现在遇到CodeIgniter的问题:我使用REST控制器库(这真的很棒)来创建API但是我无法获得PUT请求...
这是我的代码:
function user_put() {
$user_id = $this->get("id");
echo $user_id;
$username = $this->put("username");
echo $username;
}
Run Code Online (Sandbox Code Playgroud)
我使用curl来发出请求:
curl -i -X PUT -d "username=test" http://[...]/user/id/1
Run Code Online (Sandbox Code Playgroud)
user_id已满,但username变量为空.然而它适用于动词POST和GET.你有什么想法吗?
谢谢 !
jco*_*and 10
根据:http://net.tutsplus.com/tutorials/php/working-with-restful-services-in-codeigniter-2/我们应该咨询https://github.com/philsturgeon/codeigniter-restserver/blob/ master/application/libraries/REST_Controller.php#L544看到这个方法:
/**
* Detect method
*
* Detect which method (POST, PUT, GET, DELETE) is being used
*
* @return string
*/
protected function _detect_method() {
$method = strtolower($this->input->server('REQUEST_METHOD'));
if ($this->config->item('enable_emulate_request')) {
if ($this->input->post('_method')) {
$method = strtolower($this->input->post('_method'));
} else if ($this->input->server('HTTP_X_HTTP_METHOD_OVERRIDE')) {
$method = strtolower($this->input->server('HTTP_X_HTTP_METHOD_OVERRIDE'));
}
}
if (in_array($method, array('get', 'delete', 'post', 'put'))) {
return $method;
}
return 'get';
}
Run Code Online (Sandbox Code Playgroud)
看看我们是否定义了HTTP标头HTTP_X_HTTP_METHOD_OVERRIDE
,并使用它来支持我们在网络上实现的实际动词.要在请求中使用它,您可以指定标题X-HTTP-Method-Override: method
(so X-HTTP-Method-Override: put
)以生成自定义方法覆盖.有时框架期望X-HTTP-Method
而不是X-HTTP-Method-Override
这样,这取决于框架.
如果你是通过jQuery做这样的请求,你会把这个块集成到你的ajax请求中:
beforeSend: function (XMLHttpRequest) {
//Specify the HTTP method DELETE to perform a delete operation.
XMLHttpRequest.setRequestHeader("X-HTTP-Method-Override", "DELETE");
}
Run Code Online (Sandbox Code Playgroud)
小智 6
您可以尝试先检测方法类型并区分不同的情况。如果您的控制器只处理 REST 函数,那么在构造函数中放置 get 所需的信息可能会有所帮助。
switch($_SERVER['REQUEST_METHOD']){
case 'GET':
$var_array=$this->input->get();
...
break;
case 'POST':
$var_array=$this->input->post();
...
break;
case 'PUT':
case 'DELETE':
parse_str(file_get_contents("php://input"),$var_array);
...
break;
default:
echo "I don't know how to handle this request.";
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
22516 次 |
最近记录: |