开发者

json2 from multiple form fields, getting bad values in jQuery

I have a setup with multiple form fields..

<input type='text' id='Trait1' >0</input>
<input type='text' id='Trait2' >1</input>
<input type='text' id='Trait3' >2</input>
<input type='text' id='Trait4' >3</input>

(data used is just for 开发者_JAVA百科example)

When I use

$.JSON.Stringify(form.serializeArray());

I get something like..

[{'name','Trait1','value','0'}]

etc.

This doesn't translate well, because everything trying to deserialize it from json sees the 'name' and 'value' as the actual objects (where 'trait1' and '0' are the actual objects).

Is there anything I can do?


Take a look at this blog post:

http://www.foreachbit.com/2010_09_01_archive.html

or in short, you could use something like this to get rid of names and values:

  var formVals = $('#MyForm').serializeArray();
  var jsonObj = {};

  for (i in formVals)
    jsonObj[formVals[i].name] = formVals[i].value;

  var submitVals = $.toJSON({ "MyFormData": jsonObj });

Where $.toJSON is the Stringify methode.

Oh, and Harman is absolutely right. Use the value attribute in your inputs.


<input type='text' id='Trait1' >0</input> is incorrect use of the input element. Try <input type='text' id='Trait1' value='0'/>


Well you could translate it yourself:

$.JSON.Stringify($.each(form.serializeArray(), function(inp) {
  var rv = {}; rv[inp.name] = inp.value; return rv;
}));


You can easily translate form data to a JSON string like this:

allFormTags = $(document.yourFormName).serializeArray();

var myjson = {}; 
$.each(allFormTags, function() {
    myjson[this.name] = this.value;
})
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜