终于弄懂了这个级联,我去!必须得在博客记下来。
1, JS代码:
1 $(document).ready(function(){ 2 $("#select1").change(function(){ 3 adjustCountyDropDown(); 4 }); 5 }); 6 7 function adjustCountyDropDown(){ 8 var selectedCity= $("#select1").val(); 9 var county= $("#select2");10 if(selectedCity.length== 0){11 county.attr("disabled", true); 12 }13 else{14 county.attr("disabled", false);15 //ajax异步16 $.getJSON(17 'http://localhost:8080/TestStu/ajaxSelectCityTest', //ajax提交的地址,我这里是servlet文件18 {city: selectedCity}, //传递的参数,将city这个参数传到ajaxSelectCityTest这个servlet19 function(data){ //data为返回的数据20 county.empty(); //jQuery清空options21 county.append(""); 22 $.each(data, function(i, value) { 23 county.append(""); 24 });25 }26 );27 }28 }
2, 后台Servlet
package test.servlet;import java.io.IOException;import java.io.PrintWriter;import java.sql.Connection;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.ruchi.dao.impl.addDaoImpl;import com.ruchi.entity.addEntity;import com.ruchi.util.ConnectionFactory;import net.sf.json.JSONArray;public class selectCity extends HttpServlet { private static final long serialVersionUID = 7609673947157450475L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); response.setHeader("Pragam", "No-cache"); PrintWriter pw = response.getWriter(); Connection con = ConnectionFactory.getInstance().makeConnection(); try { Listlist = new ArrayList (); // String city= ${Parameter.selectedCity}; System.out.println("Before : "); String city = request.getParameter("city"); //接收来自前端传来的参数,后面的这个 city 就是第一片JS代码的第18行传来的 System.out.println("You Just Reciived: "+ city); addDaoImpl adi = new addDaoImpl(); //以下为获取后台数据 list = adi.getCountyByCity(con, city); //list为获取的所有数据 JSONArray jsonArray = JSONArray.fromObject(list); //jsonArray为list转为成的JSON数据 System.out.println(jsonArray.toString()); pw.print(jsonArray.toString()); //将jsonArray返回到前台 被第一片JS代码的第19行接收 } catch (SQLException e) { e.printStackTrace(); } finally { try { con.close(); } catch (Exception e2) { e2.printStackTrace(); } pw.close(); } }}
3, JSP页面代码:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@page import="java.util.Date"%>Insert title here 级联
4, 当然还有一些javaBean代码,操作数据库代码以及web.xml配置文件没有贴出来。
欢迎交流!