从HTTP PUT读取数据


Read data from HTTP PUT

我目前正在实现一个RESTful web服务,它使用CodeIgniter和Phil Sturgeon的REST来讨论XML。我现在纠结于如何从HTTP PUT中读取XML。我就是这么做的。

客户端:

$(function(){
    // Bind a click event to the 'ajax' object id
    $("#new_user").click(function(evt){
        // JavaScript needs totake over. So stop the browser from redirecting the page
        evt.preventDefault();
        var str = '<?xml version="1.0" encoding="UTF-8"?><xml><name>'+$("#txtname").val()+'</name><email>'+$("#txtemail").val()+'</email></xml>';
        // Ajax request to get the data
        $.ajax({
            // URL from the link that was clicked on
            url: $(this).attr("href"),
                        type: "put",
                        contentType: "application/xml",
                        processData: false,
                        data: str,
            success: function(data, textStatus, jqXHR){
                //alert('Successful AJAX request!');
                                   //var items = parseXml(data);
                                   //printXml(items);
            },
            // Failed to load request. This could be caused by any number of problems like server issues, bad links, etc.
            error: function(jqXHR, textStatus, errorThrown){
                alert('Oh no! A problem with the Ajax request!');
            }
        });
    });
});

服务器端:

public function users_put(){
    $input = file_get_contents('php://input');
    print_r($input);
}

它什么也没打印出来。以上JavaScript代码和函数在HTTP POST中运行良好。

手册中有一个很好的参考:http://php.net/manual/en/features.file-upload.put-method.php

如果不改变HTTP守护进程的设置,就不能处理PUT请求。


如果你使用的是Apache,并且可以访问mod_rewrite,在根文件夹中创建一个.htaccess文件,如:

    Options +FollowSymLinks
    RewriteEngine on
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ handler.php?uri=$1 [L,QSA]

但细节取决于HTTP守护进程(Apache, IIS, lighttpd等)和你使用的PHP框架

使用POST。您的应用程序必须确定请求是否为"PUT"。如果您指定了要修改的对象的id,那么您可以假设它是一个"PUT"请求。我不确定CodeIgniter是如何处理这个问题的,但我知道当指定id时,Zend Framework会自动路由到putAction。(例如/账户/5)