最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Serialize form inputs to JSON using Backbone.js - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question edited Jul 4, 2014 at 15:37 A.M.K 16.8k4 gold badges35 silver badges64 bronze badges asked Jan 28, 2013 at 1:03 JohnJohn 3,78914 gold badges44 silver badges49 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 5

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

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

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.

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

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();
  }
});
发布评论

评论列表(0)

  1. 暂无评论