Vinushi Lakshani
Vinushi Lakshani

Reputation: 68

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.
The alert is working fine, the execute() is not working.
When I put System.out.println("language : "+ language); in the execute() method, the output is

language : 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";    
    }

Upvotes: 4

Views: 2696

Answers (2)

Roman C
Roman C

Reputation: 1

Jquery serializes data sent as parameters using $.param internally when doing ajax request with $.ajax.

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.

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.

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.

Struts2 also can convert a string containing a comma separated values by default type conversion. For example you can see how checkbox list values are passed to struts action.

Upvotes: 2

Andrea Ligios
Andrea Ligios

Reputation: 50203

To use JSON with Struts2, your best option is to import the Struts2 JSON plugin.

Then,

  1. you'll get automatic JSON conversion when exposing data from the action to the JSP, by using the Json Result as described here, BUT
  2. you'll need to include the Json Interceptor in your interceptor stack to have the JSON conversion from the JSP to the action, as described here and here.

Upvotes: 0

Related Questions