Serialize form inputs to JSON using Backbone.js

爱⌒轻易说出口 提交于 2019-12-30 06:10:29

问题


I'm working on RESTful application - I'm using Java on the server side and Backbone for the Front End. The 2 will communicate via JSON.

My App has quite a few forms and I would like to:

  1. Serialize the form inputs to JSON
  2. Send the JSON to the server

My questions:

  1. What is the best way to serialize the form inputs to JSON? Perhaps a Backbone only solution?
  2. Once the form inputs serialized to JavaScript Objects - what is the best way to send JSON to the server?

My code so far:

Javascript and Backbone

$(function(){
    $.fn.serializeObject = function()
    {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name] !== undefined) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };

    //Model 
    var SignupForm = Backbone.Model.extend();

    //View
    var SignupView = Backbone.View.extend({
        el: '.signupForm',
        events: {
            'click input.submit': 'getStatus'
        },
        getStatus: function(event){
            var data = JSON.stringify($('form').serializeObject());
            $('.test').html(data);
            return false;
        }
    });

    var signupForm = new SignupForm();
    var signupView = new SignupView({
        model: signupForm
    });
});

HTML

<div class="signupForm">
    <form class"signup">
        <label for="name" >Name:</label>
        <input type="text" id="name" name="name" />

        <label for="surname" >Surname:</label>
        <input type="text" id="surname" name="surname" />

        <input type="submit" value="submit" class="submit" />
    </form>

    <div class="test"></div>
</div>

I'm new to Backbone so sorry if this is trivial.

I'm keen to code my application the best way as possible so please feel free to tell me if there is a better way to do this.

Thanks a lot.


回答1:


For just serializing to JSON there's this option as well

https://github.com/marioizquierdo/jquery.serializeJSON




回答2:


What is the best way to serialize the form inputs to JSON? Perhaps a Backbone only solution?

Use Backbone.Forms to read the form data into a Model.

For example:

var User = Backbone.Model.extend({
    schema: {
        title:      { type: 'Select', options: ['Mr', 'Mrs', 'Ms'] },
        name:       'Text',
        email:      { validators: ['required', 'email'] },
        birthday:   'Date',
        password:   'Password',
        address:    { type: 'NestedModel', model: Address },
        notes:      { type: 'List', listType: 'Text' }
    }
});

var user = new User();

var form = new Backbone.Form({
    model: user
}).render();

$('body').append(form.el);

Once the form inputs serialized to JavaScript Objects - what is the best way to send JSON to the server?

After that you can sync your model with your REST service. You have to set an url property on your model, and call the save method.




回答3:


Backbone doesn't make any assumptions of how you implement behavior. It only provides a clean architectural pattern. So the way you have implemented form serialization seems to be fine (similar to or adapted from: Convert form data to JavaScript object with jQuery)

As far as persistence is concerned, you can set the model's attributes when the submit button is clicked.

In your view:

getStatus: function(event){
            var data = JSON.stringify($('form').serializeObject());
            this.model.set(data);

 }

and in your model:

initialize: function(){
   //This will save attributes every time a change event is triggered.
   this.bind("change", this.save);
}



回答4:


Another solution would to be to use the backbone.syphon extension, it allows you to simply submit your form in the same way as an entity would create it:

Backbone.View.extend({
  events: {
    "submit form": "formSubmitted"
  },

  formSubmitted: function(e){
    e.preventDefault();

    var data = Backbone.Syphon.serialize(this);
    this.model.set(data);

    this.model.save();
  }
});


来源:https://stackoverflow.com/questions/14554111/serialize-form-inputs-to-json-using-backbone-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!