問題描述
我在將數組參數發送到 Struts 2 操作類時遇到問題.我正在使用 struts 2.1.8.1.
I'm having an issue sending array parameters to a Struts 2 action class. I am using struts 2.1.8.1.
下面是一些示例代碼:
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;
}
}
問題是通過jquery ajax方法發送數組時:
The problem is when sending an array via the jquery ajax method:
$.ajax({
type: 'POST',
url: 'Myaction.action',
data: {
types: ["this", "is", "a", "test"]
}
});
導致異常發生:
ognl.ParseException: 在第 1 行第 7 列遇到"]" "] "".
如何使用 jQuery 將數組發送到我的 Struts2 動作類?我需要包含類似于攔截器的東西嗎?或者 jQuery 中有一個選項可以刪除它嗎?
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?
我在使用 jQuery UI 可排序控件時也遇到了這個問題,但我使用正則表達式刪除了[]"字符解決了這個問題.我想避免這種情況,因為那個解決方案讓我很困擾.我想我可以自己構建字符串,而不是使用對象表示法,但除非你能說服我,否則我想使用對象表示法.
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 不喜歡 jQuery 1.4+ 格式,不過你可以使用傳統格式,只要把它放在你的 $.ajax()
調用:
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;
您可以在 $.param()
文檔,最好的說明是他們的簡短示例:
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"
這篇關于通過 Ajax 調用使用 Struts 2 的 HTTP 數組參數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!