简体   繁体   中英

Posting form using javascript and json with nested objects

I have an html form that has the following structure:

<input type="text" name="title" />
<input type="text" name="persons[0].name" />
<input type="text" name="persons[0].color" />
<input type="text" name="persons[1].name" />
<input type="text" name="persons[1].color" />

I would like to serialize this into the following json:

{
  "title": "titlecontent",
  "persons": [{
      "name": "person0name",
      "color": "red"
    },
    {
      "name": "person1name",
      "color": "blue"
    }
  ]
}

Notice that the number of persons can vary from case to case.

The structure of the html form can change, but the structure of the submitted json can't.

How is this done the easiest?

Dependencies:

  • locutus (npm install locutus)
  • jQuery

Code:

var parse_str = require('locutus/php/strings/parse_str');
parse_str($("#form ID").serialize(), var result = {});
console.log(result);

Hey man using jQuery and the jQuery JSON plugin , I was able to do the following: I had to change your html a bit:

<div id="Directory">
    <input type="text" class="title" />
    <span class="person 0">
        <input type="text" class="name" />
        <input type="text" class="color" />
    </span>
    <span class="person 1">
        <input type="text" class="name" />
        <input type="text" class="color" />
    </span>
</div>

And then I was able to use the following code to create your JSON array:

var Directory = {};
Directory.title = $("div#Directory input.title").val();
Directory.persons = [];
$("div#Directory span.person").each(function() {
  var index = $(this).attr("class").split(" ")[1];
  Directory.persons.push({
    name: "person" + index + $(this).children("input.name").val(),
    color: $(this).children("input.color").val(),
  });
});
alert($.toJSON(Directory));

This http ://stackoverflow.com/questions/492833/getting-correct-index-from-input-array-in-jquery is also somewhat helpful. Unfortunately I couldn't replicate their selection method with your particular set of attributes.

Hope I'm not doing your homework ;) There's a space in the URL above because I don't have enough reputation points to put more than one hyperlink.

This is your final JSON:

{
  "title": "abc",
  "persons": [{
    "name": "person0englishman",
    "color": "pink"
  }, {
    "name": "person1indian",
    "color": "brown"
  }]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM