我目前正在实现一个 RESTful 网络服务,该服务使用 CodeIgniter 处理 XML和 REST by Phil Sturgeon .我现在被困在如何从 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,请在您 PUT 到的根文件夹中创建一个 .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 框架。
关于php - 从 HTTP PUT 读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6813420/