简体   繁体   English

使用带有嵌套对象的 javascript 和 json 发布表单

[英]Posting form using javascript and json with nested objects

I have an html form that has the following structure:我有一个具有以下结构的 html 表单:

<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:我想将其序列化为以下 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. html表单的结构可以改变,但是提交的json的结构不能。

How is this done the easiest?这怎么做最简单?

Dependencies:依赖项:

  • locutus (npm install locutus) locutus(npm 安装 locutus)
  • jQuery 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:嘿,使用 jQuery 和jQuery JSON 插件的人,我能够执行以下操作:我不得不稍微更改您的 html:

<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:然后我可以使用以下代码来创建您的 JSON 数组:

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.这个 http://stackoverflow.com/questions/492833/getting-correct-index-from-input-array-in-jquery 也有点帮助。 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.希望我没有做你的功课 ;) 上面的 URL 中有一个空格,因为我没有足够的声望点来放置多个超链接。

This is your final JSON:这是您的最终 JSON:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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