最近開發中遇到了頁面傳遞數組到Action后台List類型,接受到的list對象並不是想象的按照數組元素位置對應的接受,例如數組的0位置插入到list對象的0位置,
而是數組的全部內容全部插入到了list集合的第一位置。經過反復的試驗,沒有找到很好的解決辦法,只能把這種粗糙的實現方式記錄下來,以求拋磚引玉望大家能給出更好的實現方式。
這是jsp頁面代碼:異步提交數組到Action中:
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Insert title here</title> <script src="plugin/dwz/js/jquery-1.7.2.js" type="text/javascript"></script> <script type="text/javascript"> function testceshi(log) { var v = new Array(); v = $(".testname"); var v1 = new Array(); for(var i = 0; i < v.length; i++) { v1[i] = v[i].value; } $.ajax({ url : "loginAction!testarray", type : "POST", data : "ajaxField=" + v1, success : function(data) { alert(data); } }); } </script> </head> <body> <form action="loginAction!success" method="post"> 測試<input class="testname" type="text"/><br> 測試<input class="testname" type="text"/><br> 測試<input class="testname" type="text"/><br> 測試<input class="testname" type="text"/><br> 測試<input class="testname" type="text"/><br> <input type="button" value="測試" onclick="testceshi(11)"/> </form> </body> </html>
后台java代碼:接受頁面傳遞的數組,經過測試數組全部插入到list集合的第一個位置。
@Controller @Scope("prototype") public class LoginAction extends ActionSupport { private List<String> ajaxField = new ArrayList(); public void testarray() { String str = (String) ajaxField.get(0); System.out.println(str); List<String> list = new ArrayList<String>(); String[] strs = str.split(","); for (String string : strs) { System.out.println(string); list.add(string); } for(int i = 0; i < ajaxField.size(); i++) { System.out.println(ajaxField.get(i)); } HttpServletResponse response = ServletActionContext.getResponse(); try { PrintWriter write = response.getWriter(); response.setContentType("text/html"); write.print("hello"); write.flush(); write.close(); } catch (IOException e) { e.printStackTrace(); } }
雖說實現數組傳遞的過程有點瑕疵,但是對於異步Ajax傳遞的實現方式還是正確的,對於不傳遞數組,只傳遞變量的情況,還是可以參考的。