Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

json - jquery serialize input with arrays

I have a form on my site like this:

<form id="myform" action="" method="">
 <input type="text" name="name[1][first]">
 <input type="text" name="name[2][first]">
 <input type="text" name="name[3][first]">
</form>

I want to simply grab all the data and send it to a webservice so have this js:

$fields = $('#myform').serializeArray();

Problem is, it creates the json with all the brackets shown in the input names so I get a parse error.

How can I use serializeArray and get proper json?

The resulting format that I would like to see is something like this:

{
  "name": {
    "1": {
      "first": "val1"
    },
    "2": {
      "first": "val2"
    },
    "3": {
      "first": "val3"
    }
  }
}

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I made a recursive function/plugin to do exactly this:

$.fn.serializeControls = function() {
  var data = {};

  function buildInputObject(arr, val) {
    if (arr.length < 1)
      return val;  
    var objkey = arr[0];
    if (objkey.slice(-1) == "]") {
      objkey = objkey.slice(0,-1);
    }  
    var result = {};
    if (arr.length == 1){
      result[objkey] = val;
    } else {
      arr.shift();
      var nestedVal = buildInputObject(arr,val);
      result[objkey] = nestedVal;
    }
    return result;
  }

  $.each(this.serializeArray(), function() {
    var val = this.value;
    var c = this.name.split("[");
    var a = buildInputObject(c, val);
    $.extend(true, data, a);
  });
  
  return data;
}

$("#output").html(JSON.stringify($('#myform').serializeControls(), null, 2));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<form id="myform" action="" method="">
 <input type="text" name="name[1][first]" value="beep">
 <input type="text" name="name[1][second]" value="bloop">
 <input type="text" name="name[2][first]" value="derp">
  
 <input type="text" name="foo" value="bar">  
</form>

<pre id="output">
</pre>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...