我正在尝试收集所有表单数据并将其作为 XML 发送到控制器。这个 XML 将被进一步发送到后端,后端会处理它。
JAXBMarshaller 期望为编组传入的 xml 定义一个 bean。但我没有。
要求:
$('form').submit(function () {
$.ajax({
url: $(this).attr('action'),
type: 'POST',
processData: false,
data: collectFormData1(),
headers: {
"Content-Type":"application/xml"
},
dataType: 'application/xml',
success: function (data) {
alert('Success:'+data)
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('jqXHR:'+jqXHR+'\n'+'textStatus:'+'\n'+textStatus+'errorThrown:'+errorThrown);
}
});
return false;
});
function collectFormData1()
{
//$rootElement = $('<FormXMLDoxument/>');
xmlDoc = document.implementation.createDocument("", "", null);
root = xmlDoc.createElement($('form').attr('name'));
$('form').find('div.section').each(function(index, section) {
sectionElement = xmlDoc.createElement($(section).attr('name'));
//xmlDoc.appendChild(sectionElement);
$(section).find('input').each(function(i, field) {
fieldElement = xmlDoc.createElement($(field).attr('name'));
fieldText=xmlDoc.createTextNode($(field).val());
fieldElement.appendChild(fieldText);
sectionElement.appendChild(fieldElement);
});
root.appendChild(sectionElement);
});
xmlDoc.appendChild(root);
console.log((new XMLSerializer()).serializeToString(xmlDoc));
return xmlDoc;
}
控制器
@RequestMapping(value="/save",method=RequestMethod.POST,consumes={"application/json", "application/xml", "text/xml"})
@ResponseBody public String handleSave(@RequestBody String formData)
{
System.out.println("comes here");
System.out.println(formData);//prints the form xml
return "<response>Success</response>";
}