我正在尝试序列化我的表单(JSP/Struts 1.1)并将其放入对象或 map 或 jQuery 的 .getJSON() 方法所需的任何内容中。这是我的 js 代码:
// This function makes an AJAX call, passing the entire form to the Action class
function ajaxCallWithForm(inputURL, formName, onReturnFunction)
{
var formAsMap = serializeForm(formName);
$.getJSON(inputURL, formAsMap, onReturnFunction);
}
function serializeForm(formName)
{
var obj = {};
var a = $('#'+formName).serializeArray();
$.each(a, function() {
if (obj[this.name] !== undefined) {
if (!obj[this.name].push) {
obj[this.name] = [obj[this.name]];
}
obj[this.name].push(this.value || '');
} else {
obj[this.name] = this.value || '';
}
});
return obj;
}
这会导致后端出现java.lang.IllegalArgumentException
(与 BeanUtils.populate servlet 方法有关)。
如果我将 .getJSON() 调用的 3 个参数中的第 2 个参数设置为类似这样的值,则它可以正常工作,并且数据会显示在我的 Java 后端的表单对象中:
// This function makes an AJAX call, passing the entire form to the Action class
function ajaxCallWithForm(inputURL, formName, onReturnFunction)
{
$.getJSON(inputURL, {"vehicleKeyNum":12345,
"vehicleID":"12345",
"rand":Math.random()},
onReturnFunction);
}
我还尝试使用正确的语法创建一个字符串,其中包含表单中的数据,并产生相同的结果。我的语法可能是错误的。无论如何,我的主要问题是:
1) .getJSON() 方法接受“随请求发送到服务器的映射或字符串”。作为其第二个参数(参见 http://api.jquery.com/jQuery.getJSON/ )
2)我正在传递我认为是“ map ”的东西
3) 我收到 java.lang.IllegalArgumentException
并且不知道从这里去哪里
最佳答案
如果你想向服务器提交表单,你可以简单地使用 jQuery 的 serialize()或 serializeArray()方法。
$.getJSON(inputURL, $(formName).serialize(), onReturnFunction);
如果元素名称匹配正确,您应该将serialize/serializeArray 方法返回的数据填充到表单bean 中。
here is a working example序列化方法(从jQuery网站复制)
BeanUtils.populate
servlet 方法中的 java.lang.IllegalArgumentException
是由于提交的数据与表单 Bean 上的数据之间的数据类型不匹配造成的。
关于java - 将数据传递到 jquery 的 getJSON() 时出现问题 - 不接受 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11000702/