【问题标题】:Created nested JSON from dynamic form从动态表单创建嵌套 JSON
【发布时间】:2017-11-13 00:24:09
【问题描述】:

我有一个客户自定义页面构建器,他们可以通过拖放后端构建自己的 Web 表单。

目前,我可以将数据以 JSON 格式输出,如下所示:

{ 
  "email":"xx@yy.com",
  "geoip_country":"XXYY",
  "geoip_state":"XXYY",
  "geoip_city":"XXYY",
}

但是,我需要将输出更改为以下格式,我想从表单中分离出电子邮件字段,并删除嵌套在 dynamic_attributes 部分中的所有其他数据,如下所示:

{
    "email":"xx@yy.com",
    "dynamic_attributes":{
        "geoip_country":"XXYY",
        "geoip_state":"XXYY",
        "geoip_city":"XXYY",
        // all other form fields here.

    },
}

谁能指出我正确的方向?我对输出 JSON 的经验并不丰富 - 我还应该补充一点,json 是从以下 jQuery 函数创建的:

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

        var o = {};
        var a = this.serializeArray();
        $.each(a, function () {
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };
})(jQuery);

见小提琴:https://jsfiddle.net/fish_r/m46zLdo9/3/

谢谢!

【问题讨论】:

  • dynamic_attributes 是常量属性名吗?如果不是,该属性名称来自哪里?字段如何区分为主要字段或子字段?显示一些示例 html
  • 动态属性和电子邮件都是常量属性名称,嵌套在动态属性中的数据是动态生成的。编辑添加小提琴链接
  • 所以它是一个简单的表单,并且总是有一个主要字段是email,而所有其他字段都是嵌套的?我怀疑有比这更高级别的复杂性吗?

标签: javascript jquery json api


【解决方案1】:

试试这个:

$('#myform').submit(function(e) {
    e.preventDefault();
    var data = $(this).serializeFormJSON();
    console.log(data);
});

(function ($) {
    $.fn.serializeFormJSON = function () {
		
        var o = {};
        var dynamic_attributes = {};
        var a = this.serializeArray();
        $.each(a, function () {
            if (this.name =='email') {
              if (o[this.name]) {
                  if (!o[this.name].push) {
                      o[this.name] = [o[this.name]];
                  }
                  o[this.name].push(this.value || '');
              } else {
                  o[this.name] = this.value || '';
              }
            } else {
              if (dynamic_attributes[this.name]) {
                  if (!dynamic_attributes[this.name].push) {
                      dynamic_attributes[this.name] = [dynamic_attributes[this.name]];
                  }
                  dynamic_attributes[this.name].push(this.value || '');
              } else {
                  dynamic_attributes[this.name] = this.value || '';
              }   
            }
        });
        o['dynamic_attributes'] = dynamic_attributes;
        
        return o;
    };
})(jQuery);
.hidden {opacity:.3}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="POST" id="myform">
  <input type="text" name="name" placeholder="name"><br/>
  <input type="email" name="email" placeholder="Enter your email"><br/>
  <input type="text" name="address1" placeholder="Enter the first line of your address"><br/>
  <input type="submit">
</form>
<div id="output"></div>

【讨论】:

  • 太棒了,谢谢 - 我已经很好地理解了我们是如何从顶部的 vars 创建这些的,我继续创建了另一个名为 extra_parameters 的属性,因为我们还需要那是为了我们的整合。 - 还有一个问题,你知道我怎么可能排除某些按名称/类别或 ID 输入的输入吗?
  • 忽略这一点,我已经设法通过在 jquery 中克隆表单、删除隐藏的输入然后运行 ​​serializeFormJSON() 函数来实现这一点。再次感谢孙宇。
  • 我很抱歉后来确认了 cmets。很高兴听到这个消息。
【解决方案2】:

To anyone looking for help on a similar issue in the future, I've created a library to allow forms to be sent as deep nested JSON objects by writing the name attributes of each input as a series of subkeys joined by "." characters.

要导入库:

<script src="https://cdn.jsdelivr.net/npm/deepforms@1.0.0/deepforms.min.js"></script>

使用该库制作的示例表单:

<form id = "exampleForm" method = "POST" action = "/submitForm">
    <input type = "text" name = "user.name" value = "testUser">
    <input type = "text" name = "color" value = "blue">
    <input type = "text" name = "color" value = "red">
</form>
<button onclick="document.deepforms.submitDeepForm('exampleForm')">

单击提交按钮后,将生成以下对象并作为 JSON 字符串发送:

{
    "user" : {
        "name" : "testUser"
    },
    "color" : ["blue", "red"]
}

JSON 字符串作为 deepFormJSON 参数的值发送:

deepFormJSON : '{"user":{"name":"testUser"},"color":["blue","red"]}}'

可以将其解析为 JSON 字符串,以便在请求目的地构造对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-04
    • 2019-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多