[英]Call RESTful services using Backbone by posting XML instead of JSON
我有一個像這樣的Spring RESTful服務
@RequestMapping(value = "/test", method = RequestMethod.POST, headers = { "content-type=application/xml" })
@Transactional(readOnly = false)
public @ResponseBody String saveSubscription(@RequestBody Subscription subscription) {
....
}
我的用戶界面上有Backbone代碼,
var Subscription = Backbone.Model.extend({
urlRoot :http://localhost:8087/SpringRest/test',
});
$(document).ready(function() {
$('#new-subscription').click(function(ev) {
var subscription = new Subscription({
name : $('#dropdown').val(),
type : $('input[name=type]:checked').val(),
format : $('input[name=format]:checked').val(),
});
subscription.save();
});
通過使用此代碼,我將調用Spring REST服務。 在這里,骨干網將訂閱數據發布為JSON。
但是我想將其發布為XML,然后在訪問該服務時將進行春季解組。
從客戶端訪問服務之前,如何將Backbone模型JSON解析為XML?
您可以通過覆蓋sync
方法來修改Backbone同步數據的方式。 例如,您的模型定義可能看起來像
var Subscription = Backbone.Model.extend({
urlRoot: 'http://localhost:8087/SpringRest/test',
sync: function(method, model, options) {
if ((method !== "create") && (method !== "update"))
return Backbone.sync.apply(this, arguments);
options = options || {};
// what the server responds with
options.dataType = 'xml';
// the content type of your data
options.contentType = 'application/xml';
// what you send, your XML
// you will have to tailor it to what your server expects
var doc = document.implementation.createDocument(null, "data", null);
_.each(this.toJSON(), function(v, k) {
var node = doc.createElement(k);
var text = doc.createTextNode(v);
node.appendChild(text);
doc.documentElement.appendChild(node);
});
options.data = doc;
return Backbone.sync.call(this, method, model, options);
}
});
那會發送
<data>
<name>...</name>
<type>...</type>
<format>...</format>
</data>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.