前台:
function getUserByName(){$.getJSON("getStudent?jsoncallback=?",function(data){//alert(data);$.each(data,function(i,item){var tr="<tr><td>"+item.name+"</td><td>"+item.age+"</td></tr>";//alert(item.name+":"+item.age);$("#info").append(tr);});});}
後台組織json資料:
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {List<Student> sts = new ArrayList<Student>();sts.add(new Student("鳴人",18));sts.add(new Student("佐助",19));sts.add(new Student("小櫻",20));sts.add(new Student("卡卡西",21));System.out.println("111111111111111");//組織json資料String jsoncallback = request.getParameter("jsoncallback");System.out.println(jsoncallback);String json = "";StringBuffer sbjson = new StringBuffer(jsoncallback+"([");for(Student st : sts){sbjson.append("{name:\""+st.getName()+"\",age:"+st.getAge()+"},");}sbjson.append("])");json = sbjson.toString();System.out.println(json);response.setCharacterEncoding("utf-8");response.setContentType("text/json");PrintWriter out = response.getWriter();out.print(json);out.flush();out.close();}