[英]How to send javascript array to struts action by using jQuery Ajax
I am new to Struts 2. I want to send a javascript array to a Struts action class by using jQuery AJAX request. 我是Struts 2的新手。我想通过使用jQuery AJAX请求将一个javascript数组发送到Struts动作类。
The alert is working fine, the execute()
is not working. 警报工作正常,
execute()
不起作用。
When I put System.out.println("language : "+ language);
当我把
System.out.println("language : "+ language);
in the execute()
method, the output is 在
execute()
方法中,输出是
language :
null
.语言:
null
。
var langArr = [];
$("#language").each(function()
{
var selectedLang = $("select").val();
var selectedValues = $(this).val();
langArr.push(selectedValues);
});
alert("Languages : " + langArr);
$.ajax({
method: "POST",
url: "getProjectPost",
data: { "language" : langArr },
dataType : "json",
traditional: true,
success:
function()
{
alert("Success");
},
error:
function()
{
alert("Error");
}
});
This is my action class 这是我的动作类
public class ProjectPostAction {
private int[] language;
public final int[] getLanguage() {
return language;
}
public final void setLanguage(int[] language) {
this.language = language;
}
public String execute() throws Exception {
System.out.println("language : "+ language[0]);
return "success";
}
Jquery serializes data sent as parameters using $.param
internally when doing ajax request with $.ajax
. 当使用
$.ajax
执行ajax请求时,Jquery在内部使用$.param
序列化作为参数发送的数据。
The data should be set as array of integers or string with comma separated list of integers, so jQuery can correctly serialize it before sending with the request. 数据应设置为整数数组或带逗号分隔的整数列表的字符串,因此jQuery可以在发送请求之前正确序列化它。
You can send an array parameter to struts2 only with traditional
setting because struts using type conversion to populate a property of the action using keys as parameter names. 您只能使用
traditional
设置将数组参数发送到struts2,因为struts使用类型转换来使用键作为参数名称来填充操作的属性。
So, the array should be an array of primitive integers but your array contains other objects that are not primitive integers. 因此,数组应该是一个原始整数数组,但是您的数组包含其他非原始整数的对象。
To demonstrate you can see this demo to understand how to get parameter values and serialize it the same way like is doing $.ajax
. 为了演示你可以看到这个演示,以了解如何获取参数值并以与执行
$.ajax
相同的方式序列化它。
Struts2 also can convert a string containing a comma separated values by default type conversion. Struts2还可以通过默认类型转换转换包含逗号分隔值的字符串。 For example you can see how checkbox list values are passed to struts action .
例如,您可以看到复选框列表值如何传递给struts操作 。
To use JSON with Struts2, your best option is to import the Struts2 JSON plugin . 要在Struts2中使用JSON,最好的选择是导入Struts2 JSON插件 。
Then, 然后,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.