gpt4 book ai didi

php - 使用 Codeigniter 获取 PUT 请求

转载 作者:可可西里 更新时间:2023-11-01 12:31:05 25 4
gpt4 key购买 nike

我现在在使用 CodeIgniter 时遇到问题:我使用 REST Controller library (这真的很棒)创建一个 API 但我无法获得 PUT 请求...

这是我的代码:

function user_put() {
$user_id = $this->get("id");
echo $user_id;
$username = $this->put("username");
echo $username;
}

我使用 curl 来发出请求:

curl -i -X PUT -d "username=test" http://[...]/user/id/1

user_id 已满,但 username 变量为空。然而,它适用于动词 POST 和 GET。请问你有什么想法吗?

谢谢!

最佳答案

根据: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';
}

查看我们是否已经定义了 HTTP header HTTP_X_HTTP_METHOD_OVERRIDE 并且它使用它来支持我们在网络上实现的实际动词。要在请求中使用它,您需要指定 header X-HTTP-Method-Override: method(因此 X-HTTP-Method-Override: put)以生成自定义方法覆盖。有时框架需要 X-HTTP-Method 而不是 X-HTTP-Method-Override 所以这因框架而异。

如果您通过 jQuery 执行这样的请求,您可以将此 block 集成到您的 ajax 请求中:

beforeSend: function (XMLHttpRequest) {
//Specify the HTTP method DELETE to perform a delete operation.
XMLHttpRequest.setRequestHeader("X-HTTP-Method-Override", "DELETE");
}

关于php - 使用 Codeigniter 获取 PUT 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5540781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com