用ajax+servlet实现二级联动(以省份与城市为例)

1.实现思路:

在下拉列表框中编写js函数触发onchange事件,在这js函数中将选中的name值通过ajax传给后台servlet,在servlet中通过request.getParameter("name")获得选中的name,调用后台的方法得到相应的城市列表(此例没有数据库)。然后如果查到响应的城市的话将其列表组成一个用"#"号分割的字符串str,将其放到response的Writer中。然后在回调函数中接受应答字符串str,调用split("#")方法得到相应的城市数组,然后取得index.jsp的下拉列表框ID,将相应的城市用循环动态的加入到城市列表框中。

2.具体例子

(1)index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); %> 以城市与省份为例,用ajax实现二级联动

选择省份: 城市:

(2)GetCity.java

import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class GetCity extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.reset(); String name=request.getParameter("provinceName")==null?"":request.getParameter("provinceName"); System.out.print(name); String str=""; if(name.trim().equals("guangdong")){ str="广州#深圳#东莞#中山#珠海#惠东"; }else if(name.trim().equals("ningxia")){ str="银川#吴忠#中卫#中宁#固原"; }else{ str="没有数据"; } response.setContentType("text/html"); response.setCharacterEncoding("utf-8"); response.getWriter().write(str); response.getWriter().flush(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }

(3)web.xml

This is the description of my J2EE component This is the display name of my J2EE component GetCity GetCity GetCity /GetCity index.jsp

3.运行效果:

你可能感兴趣的:(用ajax+servlet实现二级联动(以省份与城市为例))