简体   繁体   中英

Call RESTful services using Backbone by posting XML instead of JSON

I have a Spring RESTful service like

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

And my UI has Backbone code is like,

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();
        });

By using this code, I call the Spring REST service. Here Backbone post subscription data as JSON.

But I want to post it as XML then spring unmarshalling will happen when hit the service.

How can I parse Backbone model JSON to XML before I hit the service from client side?

You can modify how Backbone synchronizes the data by overriding the sync methods. For example, you model definition could look like

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);
    }
});

That would send

<data>
    <name>...</name>
    <type>...</type>
    <format>...</format>
</data>

And a demo http://jsfiddle.net/nikoshr/uwhd3tk5/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM