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?

3
  • 3
    Try setting traditional: true, in your ajax request Commented Apr 22, 2015 at 17:41
  • 2
    What exactly is being sent? Post output from dev network console. Commented Apr 22, 2015 at 19:19
  • Thanks @Musa, it made the trick. I already had tried $.ajaxSettings.traditional = true; (saw it here), 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. Commented Apr 23, 2015 at 13:57

1 Answer 1

10

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";
        }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.