通过发布XML而不是JSON来使用Backbone调用RESTful服务

时间:2015-02-13 15:43:37

标签: xml json spring-mvc backbone.js

我有像

这样的Spring RESTful服务
  @RequestMapping(value = "/test", method = RequestMethod.POST,  headers = { "content-type=application/xml" })
  @Transactional(readOnly = false) 
  public @ResponseBody String saveSubscription(@RequestBody Subscription subscription) {
   ....
  }

我的UI有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服务。这里Backbone将订阅数据发布为JSON。

但我希望将其发布为XML,然后在点击服务时弹出解组。

在从客户端点击服务之前,我如何解析Backbone模型JSON到XML?

1 个答案:

答案 0 :(得分:2)

您可以通过覆盖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>

演示http://jsfiddle.net/nikoshr/uwhd3tk5/