Javascript 解析json表单数据以提交给API
我需要将表单数据作为JSON提交给API。以下是我的序列化表单数据片段:Javascript 解析json表单数据以提交给API,javascript,json,Javascript,Json,我需要将表单数据作为JSON提交给API。以下是我的序列化表单数据片段: { "Type":["foo", "bar", "blah"], } (function ($) { $.fn.serializeFormJSON = function () { var o = {}; var a = this.serializeArray(); $.each(a, function () {
{
"Type":["foo", "bar", "blah"],
}
(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)
API要求以以下格式提交数据:
{
"Type":"foo,bar,blah",
}
我正在寻找一种基于解析器的方法来转换这些数据,而不是求助于replace/regex
。欢迎任何建议
我正在使用此函数序列化表单数据:
{
"Type":["foo", "bar", "blah"],
}
(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)
然后将数据发布到API,如下所示:
$("#contactForm").submit( function(event) {
event.preventDefault();
var formData = $(this).serializeFormJSON();
var settings = {
"async": true,
"crossDomain": true,
"url": "the submit URL",
"method": "POST",
"headers": {
"Content-Type": "application/json",
"Cache-Control": "no-cache",
},
"processData": false,
"data": JSON.stringify(formData),
}
$.ajax(settings).done(function (response) {
console.log(response);
});
});
您可以使用
数组连接数组。连接(',')
您可以通过对象循环检查值是否为数组,然后使用连接元素。连接(',')
并在对象中替换它们,如:
var obj={
“类型1”:[“foo”、“bar”、“blah”],
“类型2”:[“foo”,“blah”],
“Type3”:[“bar”,“blah”],
};
for(obj中的var键){
if(对象hasOwnProperty(键)){
if(Array.isArray(obj[key])){
obj[key]=obj[key].连接(',');
}
}
}
控制台日志(obj)代码>只需使用JavaScripttoString()
。简单易用
单键:
var obj = {
"Type": ["foo", "bar", "blah"]
};
obj['Type'] = obj['Type'].toString();
// obj = {Type: "foo,bar,blah"}
多键:
var obj = {
"Type1": ["foo", "bar", "blah"],
"Type2": ["foo", "blah"],
"Type3": ["bar", "blah"]
};
for(k in obj) obj[k] = obj[k].toString();
// obj = { Type1: "foo,bar,blah", Type2: "foo,blah", Type3: "bar,blah" }
如果所有参数都需要为字符串,那么这将非常有用,但并非所有参数都需要为字符串:
var obj = {
"Type1": ["foo", "bar", "blah"],
"Type2": 888888888,
"Type3": "foo",
"Type4": "342333",
"Type5": ["bar"]
};
for(k in obj) obj[k] = obj[k].toString();
// obj = { Type1: "foo,bar,blah", Type2: "888888888", Type3: "foo", Type4: "342333", Type5: "bar" }
你是如何创建表单数据的?工作起来很有魅力。非常感谢你的帮助!