开发者

HTTP Array Parameters with Struts 2 via an Ajax Call

开发者 https://www.devze.com 2023-01-11 20:30 出处:网络
I\'m having an i开发者_运维问答ssue sending array parameters to a Struts 2 action class.I am using struts 2.1.8.1.

I'm having an i开发者_运维问答ssue sending array parameters to a Struts 2 action class. I am using struts 2.1.8.1.

Here is some example code:

public class MyAction extends ActionSupport {

    private String[] types;

    public String execute() {
        return SUCCESS;
    }

    public String[] getTypes() {
        return types;
    }

    public void setTypes(String[] types) {
        this.types = types;
    }
}

The problem is when sending an array via the jquery ajax method:

$.ajax({
    type: 'POST',
    url: 'Myaction.action',
    data: {
        types: ["this", "is", "a", "test"]
    }
});

causes an exception to occur:

ognl.ParseException: Encountered " "]" "] "" at line 1, column 7.

How can I use jQuery to send the array to my Struts2 action class? Is there something along the lines of an interceptor that I need to include? Or is there an option in jQuery to remove this?

I also encountered this problem with the jQuery UI Sortable control, but I solved that using a regex to remove the "[]" characters. I would like to avoid that, because that solution bothers me. I suppose I could just build the string myself, instead of using the object notation, but unless you can convince me otherwise, I would like to use the object notation instead.


IIRC Struts doesn't like the jQuery 1.4+ format, you can use the traditional format though, just put this any time before your $.ajax() call:

$.ajaxSettings.traditional = true; 

You can read more about the 1.4+ default vs traditional serialization in the $.param() documentation, the best illustration is their short example:

// <=1.3.2: (traditional in 1.4+)
$.param({ a: [2,3,4] }) // "a=2&a=3&a=4"
// >=1.4: (default in 1.4+)
$.param({ a: [2,3,4] }) // "a[]=2&a[]=3&a[]=4"
0

精彩评论

暂无评论...
验证码 换一张
取 消