要更新资源,可以使用POST和x-http-method-override进行修补。这是一个有效的RESTful操作,使用POST将与防火墙和较老的用户代理更加兼容。请求中的数据应指明要更新的内容。
var url = '/api/posts/5707702298738688'
var patch_ops = [
{ "op": "replace", "path": "/properties/", "author": text}
{ "op": "add", "path": "/replies/", {"author": text, "comment":"blah"}}
/*
{ "op": "remove", "path": "https://stackoverflow.com/a/b/c" },
{ "op": "add", "path": "https://stackoverflow.com/a/b/c", "value": [ "foo", "bar" ] },
{ "op": "replace", "path": "https://stackoverflow.com/a/b/c", "value": 42 },
{ "op": "move", "from": "https://stackoverflow.com/a/b/c", "path": "https://stackoverflow.com/a/b/d" },
{ "op": "copy", "from": "https://stackoverflow.com/a/b/d", "path": "https://stackoverflow.com/a/b/e" }
*/
];
var xhr = jQuery.ajax({
type: "POST",
beforeSend: function (request)
{
request.setRequestHeader("X-HTTP-Method-Override", "PATCH");
},
url: url,
data: my_json_string,
dataType:"json",
success: function(data) {
return data;
},
error: function(xhr, textStatus, error){
return error;
}
});
服务器处理器:
def post(self, object_name):
if self.request.headers['x-http-method-override'] == 'PATCH':
# update according to patch operations
patch_ops_str= self.request.body.decode('utf-8')
try:
patch_ops = json.loads(new_area_geojson_str)
except:
self.response.set_status(400)
return self.response.out.write('{"status": "error", "reason": "JSON Parse error" }')
else:
self.response.set_status(405)
return self.response.out.write('{"status": "error", "reason": "post not accepted without x-http-method-override to PATCH" }')
从Please do not patch like an idiot
这固定的问题涉及在URL中的PATCH方法获取服务,而不是开发Web服务器调整。 [问题975](https://code.google.com/p/googleappengine/issues/detail?id=975)表示PROPPPATCH可以修复WebDAV支持,并且开发Web服务器上仍不支持PATCH :-( –