ajax從後臺返回list類型到前臺解析

前臺:

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();
	}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章