Is there javascript (prefer jquery) library that automatically maps form elements to JSON?
Background: This is something I have been looking for since before even JSON was known as JSON.
Suppose you have the following javascript variable inside your code:
jsonroot =
{
'fname':'valued'
,'lname':'customer'
,faves:['berry','chocolate','mint']
,actors:[
{'fname':'brad','lname':'pitt'}
,{'fname':'mike','lname':'hammer'}
]
};
You can easily see how this maps to JSON, it is a 1:1 correspondence.
Question: Is there a library that can take this 1:1 correspondence and carry it over to HTML Form elements? For example, I would like to do something like this inside a FORM element:
<input type="text" mapping="jsonroot['fname']" id="fname"></in开发者_如何学JAVAput>
<input type="text" mapping="jsonroot['lname']" id="lname"></input>
<legend>
<fieldset>Favorite Flavors</fieldset>
<input type="text" mapping="jsonroot['faves'][0]" id="fave_0"></input>
<input type="text" mapping="jsonroot['faves'][1]" id="fave_1"></input>
<input type="text" mapping="jsonroot['faves'][2]" id="fave_2"></input>
</legend>
<legend>
<fieldset>Favorite Actors</fieldset>
<input type="text" mapping="jsonroot['actors'][0]['fname']" id="fave_0_fname"></input>
<input type="text" mapping="jsonroot['actors'][0]['lname']" id="fave_0_lname"></input>
<input type="text" mapping="jsonroot['actors'][1]['fname']" id="fave_1_fname"></input>
<input type="text" mapping="jsonroot['actors'][1]['lname']" id="fave_1_lname"></input>
</legend>
Rationale: Sometimes, instead of submitting form variables via POST or GET, I want to pass them into a javascript variable, then do something with the variable, and then send it somewhere.
Writing the HTML Form <-> JSON translation is tedious. I can't be the only person out there who has wanted to to this, so is there a library that handles this automatically?
Use something like Mark Gibson's JSON JQuery plugin. It adds $.toJSON()
and $.parseJSON()
methods. Use this in combination with code that serializes a form to an object such as Serialize Form to JSON:
$.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; };
精彩评论