package com.kaishengit.web; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONArray; import com.kaishengit.dao.TypeDao; import com.kaishengit.vo.Type; public class TypeServlet extends HttpServlet { private static final long serialVersionUID = -8422243849837658057L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF-8"); String id = request.getParameter("id"); TypeDao dao = new TypeDao(); List<Type> list = dao.findByFid(Integer.valueOf(id)); //System.out.println(list.size()); //response.setContentType("text/xml"); PrintWriter out = response.getWriter(); /*out.println("<?xml version=/"1.0/" encoding=/"UTF-8/"?>"); out.println("<types>"); for(Type type : list){ out.println("<type id=/""+type.getId()+"/" fid=/""+type.getFid()+"/">"+type.getTypeName()+"</type>"); } out.println("</types>");*/ JSONArray json = JSONArray.fromObject(list); out.println(json.toString()); //out.println("alert('HAHA!')"); out.flush(); out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } } <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'type.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <mce:script type="text/javascript" src="js/json.js" mce_src="js/json.js"></mce:script> <mce:script type="text/javascript" src="js/jquery.js" mce_src="js/jquery.js"></mce:script> <mce:script type="text/javascript"><!-- $(document).ready(function(){ $("#f").change(function(){ var v = $(this).val(); $.getJSON("type.do",{id:v},function(json){ //document.getElementById("s").options.length = 1; $("#s").children().each(function(){ if($(this).val() != 0){ $(this).remove(); } }); $(json).each(function(){ var id = this.id; var fid = this.fid; var typeName = this.typeName; //alert(typeName); //var option = new Option(typeName,id); //document.getElementById('s').options.add(option); $("<option></option>").attr("value",id).text(typeName).appendTo($("#s")); }); }); }); }); // --></mce:script> </head> <body> <select id="f"> <option value="0">--请选择父类--</option> <option value="1">计算机类</option> <option value="2">管理类</option> <option value="3">文史类</option> <option value="4">美学类</option> </select> <select id="s"> <option value="0">--请选择类别--</option> </select> </body> </html>