要更新資源,可以使用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 :-( –