利用ajax傳list道後臺,後臺返回list到ajax
阿新 • • 發佈:2019-01-10
後臺程式碼:
HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = null; JSONArray mlist = JSONArray.fromObject(list); //有依賴jar包 try { out = response.getWriter(); out.print(mlist.toString()); } catch (IOException e) { e.printStackTrace(); } finally { out.flush(); out.close(); }
JSONArray依賴jar包:
commons-lang.jar
commons-beanutils.jar
commons-collections.jar
commons-logging.jar
ezmorph.jar
json-lib-2.2.2-jdk15.jar
如果還是報錯,看看包導的正確不正確。其中,commons-lang.jar 和 commons-lang3-3.2.jar是不一樣的
前臺程式碼:
$.ajax({ type:"POST", url:"accountAction!queryUMajor", data:"deptId="+$("#deptId").val(), dataType:"text", success:function(list){ var majorList=eval("("+list+")");//處理,將json字串轉換為物件 $.each(majorList, function (i, item) { alert(item.id + "," + item.name); }); }, error:function(err){ alert(err); } });