gpt4 book ai didi

javascript - 从动态表单创建嵌套的 JSON

转载 作者:行者123 更新时间:2023-11-30 20:59:41 25 4
gpt4 key购买 nike

我有一个为客户定制的页面构建器,他们可以通过拖放后端构建自己的 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);

参见 fiddle :https://jsfiddle.net/fish_r/m46zLdo9/3/

谢谢!

最佳答案

试试这个:

$('#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>

关于javascript - 从动态表单创建嵌套的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47255531/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com