3

So far, I've been able to send a simple string to a Struts2 action class, via an AJAX call. This time I need to do the same, but with a String array, and so I've changed my code like this:

1. AJAX call:

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, the data isn't arriving to the action calss. Also, I keep getting this warning, which of course must be the key to my problem:

WARNING: Parameter [test[]] didn't match acceptedPattern pattern!

Maybe this is some kind of configuration issue?

João Fernandes
  • 558
  • 3
  • 11
  • 29
  • 3
    Try setting `traditional: true,` in your ajax request – Musa Apr 22 '15 at 17:41
  • 2
    What exactly is being sent? Post output from dev network console. – Aleksandr M Apr 22 '15 at 19:19
  • Thanks @Musa, it made the trick. I already had tried `$.ajaxSettings.traditional = true; ` (saw it [here](http://stackoverflow.com/questions/3508550/http-array-parameters-with-struts-2-via-an-ajax-call)), with no effect. If you post it as an answer I'll accept it, of course. @AleksandrM, besides this test it will be an array containing the IDs of a set of (checked) checkboxes in a table. – João Fernandes Apr 23 '15 at 13:57

1 Answers1

9

jQuery.ajax's default serialization for arrays appends a [] after the name (eg test[]=1&test[]=2), while frameworks like PHP recognizes this format, struts doesn't. In order to prevent this behaviour add the traditional: true, configuration 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";
        }
});
Musa
  • 96,336
  • 17
  • 118
  • 137