views:

169

answers:

1

I've been working with the JTemplates plugin which I've used to create a form that is bound to a json object via a template. Works perfectly. What I would like to do though is instead of submitting the form I'd like to re-serialize it back into the json object from which it originated and pass it back to the controller method as a json string. What's the best way to serialize the object back into its original format?

A: 

I use serializeObject and toJson to accomplish this.

var yourForm = $('#formId');
//Serialize form elements and make into json object
var jsonObject = $.toJSON(yourForm.serializeObject());

serializeObject (jquery)

$.fn.serializeObject = function()
{
   var o = {};
   var a = this.serializeArray();
   $.each(a, function() {
       if (o[this.name]) {
           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;
};

toJSON

http://json.org/json2.js

Amin