我有一个表单,该表单用于将JSON键值对中的表单数据发布到URL。与以下格式相同:
[{'name':'URL','value':'http://127.0.0.1:8000/test/addcustomer'}, {'name':'FirstName','value':'Abc'},{'name':'LastName','value': 'Xyz'},{'name':'DOB','value':'123457'},{'name':'EmailAddress', 'value':'example@gmail.com'},{'name':'Address1','value':'123 街道”},{'名称':'地址2','值':'11123'},{'名称':'城市', 'value':'Xyz'},{'name':'State','value':'Pqr'},{'name': 'PostalCode','value':'12345'}]
相反,我想要的是以下内容:
[{'URL':'http://127.0.0.1:8000/test/addcustomer', '名字':'Abc','姓氏':'Xyz','DOB':'123457', '电子邮件地址':'example@gmail.com','地址1':'123 街道”,“地址2”:“ 11123”,“城市”:“ Xyz”,“州”:“ Pqr”,“邮政编码”:“ 12345”}]
请参考以下代码:
$(document).ready(function(){
$("#submit").on('click', function(){
var a=document.forms["myForm"]["EmailAddress"].value;
var b=document.forms["myForm"]["URL"].value;
if (a==null || a=="" || b==null || b=="")
{
$("#EmailAddress").css("border-color", "#963634");
$("#URL").css("border-color", "#963634");
alert("Please fill Email Address and URL!!!");
return false;
}
else
$.ajax({
url: b,
type : "POST",
data : JSON.stringify($("#myForm").serializeArray()),
success : function(result) {
alert(result);
$("#myForm")[0].reset();
},
error: function() {
alert('Please enter valid URL');
}
})
});
});
答案 0 :(得分:0)
我会尝试:
else
{
let formData = $("#myForm").serializeArray();
let data = formData.reduce((acc, x) => acc[x.name] = x.value, {});
$.ajax({
url: b,
type : "POST",
data : JSON.stringify(data),
success : function(result) {
alert(result);
$("#myForm")[0].reset();
},
error: function() {
alert('Please enter valid URL');
}
})
}
reduce行大致等于:
// formData is in the form [ {'name': 'A', 'value': B}, {'name': 'X', 'value': Y},... ]
let data = {};
for (let item of formData)
data[item.name] = item.value;
// data is now in the form { 'A': B, 'X': Y, ... }