开发者

Read data from HTTP PUT

I am currently implementing a RESTful web service which talks XML using CodeIgniter and REST by Phil Sturgeon. I am now stuck at how to read XML from HTTP PUT. This is what I did.

At the client side:

$(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!');
            }
        });
    });
});

At the server side:

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

It prints out nothing. The above JavaScript code and function works well in HTTP POST.


The manual has a good reference for that: http://php.net/manual/en/features.file-upload.put-method.php

You cannot handle PUT requests without altering the HTTP daemon's setup.


If you're using Apache and have access to mod_rewrite, make a .htaccess file in the root folder that you PUT to with something like:

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

But the details depend on what HTTP daemon (Apache, IIS, lighttpd, etc) and which PHP framework you use.


Use POST. Your application will have to determine if the request is a 'PUT' or not. If you specify the id of the object that you are modifying then you can assume it is a 'PUT' request. I'm not sure how CodeIgniter handles this, but I do know that Zend Framework automatically routes to the putAction when the id is specified. (e.g. /account/5)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜