简体   繁体   English

使用嵌入对象序列化HTML表单

[英]Serialize HTML Form with Embedded Objects

I have the following form ... 我有以下表格......

<form id="my-form">

  <fieldset name="address">
    <input name="streetAddress" type="text" placeholder="Street Address"><br>
    <input name="city"          type="text" placeholder="City"><p>,</p>
    <input name="state"         type="text" placeholder="State">
    <input name="zipCode"       type="text" placeholder="Zip Code">
  </fieldset>

  <fieldset name="dimensions">
    <input name="length" type="text" placeholder="length">
    <input name="width"  type="text" placeholder="width">
    <input name="height" type="text" placeholder="height">
  </fieldset>

</form>

I need to serialize it into JSON with JS, but I need to have the address's fields warped in an address object, and the dimensions's fields warped in a dimensions object. 我需要使用JS将其序列化为JSON,但是我需要在地址对象中使地址的字段变形,并且维度的字段在维度对象中变形。

Something like this ... 像这样......

{
    'address':{'streetAddress':'111 Candy Ln', 'city':'Los Angeles', ...}, 
    'dimensions':{...}
}

How do you do this cleanly, idealy without having to write my own function for doing this? 你如何干净利落地完成这项工作,而不必编写我自己的功能来做到这一点? I have of course seen scripts to serialize, but nothing that will do embedded objects. 我当然看到要序列化的脚本,但没有任何可以做嵌入式对象的脚本。

Have you tried putting all the fields into arrays? 您是否尝试将所有字段放入数组?

<fieldset name="address">
<input name="address[streetAddress]" type="text" placeholder="Street Address"><br>
<input name="address[city]" type="text" placeholder="City"><p>,</p>
<input name="address[state]" type="text" placeholder="State">
<input name="address[zipCode]" type="text" placeholder="Zip Code">
</fieldset>

Heres an example, using the serializeObject plugin 下面是一个使用serializeObject插件的例子

Just include that script and you can convert any form into a multi layered JSON object. 只需包含该脚本,您就可以将任何表单转换为多层JSON对象。

DEMO HERE 在这里演示

Using this plugin...more info here Convert form data to JavaScript object with jQuery 使用此插件...更多信息在这里使用jQuery将表单数据转换为JavaScript对象

(function($){
$.fn.serializeObject = function(){

    var self = this,
        json = {},
        push_counters = {},
        patterns = {
            "validate": /^[a-zA-Z][a-zA-Z0-9_]*(?:\[(?:\d*|[a-zA-Z0-9_]+)\])*$/,
            "key":      /[a-zA-Z0-9_]+|(?=\[\])/g,
            "push":     /^$/,
            "fixed":    /^\d+$/,
            "named":    /^[a-zA-Z0-9_]+$/
        };


    this.build = function(base, key, value){
        base[key] = value;
        return base;
    };

    this.push_counter = function(key){
        if(push_counters[key] === undefined){
            push_counters[key] = 0;
        }
        return push_counters[key]++;
    };

    $.each($(this).serializeArray(), function(){

        // skip invalid keys
        if(!patterns.validate.test(this.name)){
            return;
        }

        var k,
            keys = this.name.match(patterns.key),
            merge = this.value,
            reverse_key = this.name;

        while((k = keys.pop()) !== undefined){

            // adjust reverse_key
            reverse_key = reverse_key.replace(new RegExp("\\[" + k + "\\]$"), '');

            // push
            if(k.match(patterns.push)){
                merge = self.build([], self.push_counter(reverse_key), merge);
            }

            // fixed
            else if(k.match(patterns.fixed)){
                merge = self.build([], k, merge);
            }

            // named
            else if(k.match(patterns.named)){
                merge = self.build({}, k, merge);
            }
        }

        json = $.extend(true, json, merge);
    });

    return json;
};
})(jQuery);

I have two solutions for this: 我有两个解决方案:

  1. Name the fields after the fieldsets (like the proposal above): address[street], address[zipcode], etc . 在字段集之后命名字段(如上面的提议): address[street], address[zipcode], etc
  2. Give the fieldsets some unique id's. 为fieldsets提供一些唯一的id。

In both cases I suggest you using this library I made: https://github.com/serbanghita/formToObject 在这两种情况下,我建议你使用我制作的这个库: https//github.com/serbanghita/formToObject

Call it like this: 像这样称呼它:

Case 1: var myFormObj = new formToObject('myFormId'); 案例1: var myFormObj = new formToObject('myFormId');

Case 2: var myFormObj = new formToObject('myFieldsetId'); 案例2: var myFormObj = new formToObject('myFieldsetId');

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

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