Send array to Struts2 action with jQuery AJAX call
So far, I've managed to send a simple string to the Struts2 action class using an AJAX call. This time I need to do the same thing but with a String array, so I changed my code like this:
1. Calling AJAX:
var test = [1, 2, 3, 4, 5];
$.ajax({
method: "POST",
url: "createexperiment4.action",
data: { test : test },
success:
function()
{
window.location = "loadexperiments.action";
}
});
2. CreateExperiment4Action.java:
private String[] test;
[...]
public void setTest(String[] test)
{
this.test = test;
}
However, no data is fed to the calss action. Also, I keep getting this warning, which of course must be the key to my problem:
WARNING: The [test []] parameter does not match the accepted Pattern!
Could it be some kind of configuration issue?
source to share
jQuery.ajax default serialization for arrays adds []
after the name (for example test[]=1&test[]=2
), whereas frameworks like PHP recognize this format, struts don't. To prevent this behavior add config traditional: true,
to your ajax request which will give something like test=1&test=2
.
var test = [1, 2, 3, 4, 5];
$.ajax({
method: "POST",
url: "createexperiment4.action",
data: { test : test },
traditional: true,
success:
function()
{
window.location = "loadexperiments.action";
}
});
source to share