Ajax学习之------>Ajax和Json实现无限下拉框联动(上)

前端之家收集整理的这篇文章主要介绍了Ajax学习之------>Ajax和Json实现无限下拉框联动(上)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

init.jsp页面,直接跳转到InitShengServlet2这个servlet初始化省份
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<jsp:forward page="/InitShengServlet2"></jsp:forward>

/**

该servlet初始化完后跳转到list4.jsp

*/
InitShengServletInitShengServlet

package com.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.dao.CityDao;
@SuppressWarnings("serial")
public class InitShengServlet2 extends HttpServlet {
	public void doGet(HttpServletRequest request,HttpServletResponse response)
			throws ServletException,IOException {
		CityDao cityDao=new CityDao();
		request.setAttribute("shengList",cityDao.findByParentId(0));
		request.getRequestDispatcher("list4.jsp").forward(request,response);
	}

	public void doPost(HttpServletRequest request,IOException {
		doGet(request,response);
	}

}

/**

数据库操作的工具类

*/

package com.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.sqlException;

public class DBManager {
	public Connection getCon() {
		try {
			Class.forName("com.microsoft.sqlserver.jdbc.sqlServerDriver");
			return DriverManager.getConnection(
					"jdbc:sqlserver://127.0.0.1:1433;DatabaseName=cityManager","sa","sasa");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (sqlException e) {
			e.printStackTrace();
		}
		return null;
	}

	// 查询结果
	public ResultSet query(String sql,Object... p) {
		Connection con = getCon();
		PreparedStatement ps = null;
		try {
			 ps= con.prepareStatement(sql);
			if (p != null)
				for (int i = 0; i < p.length; i++) {
					ps.setObject(i + 1,p[i]);
				}
			return ps.executeQuery();
		} catch (sqlException e) {
			e.printStackTrace();
		}
		return null;
	}

	// 增删改
	public int update(String sql,Object... p) {
		Connection con = getCon();
		PreparedStatement ps=null;
		try {
			 ps= con.prepareStatement(sql);
			if (p != null)
				for (int i = 0; i < p.length; i++) {
					ps.setObject(i + 1,p[i]);
				}
			return ps.executeUpdate();
		} catch (sqlException e) {
			e.printStackTrace();
			throw new RuntimeException("增删改失败");
		}finally{
			this.closePrepStmt(ps);
			this.closeConnection(con);
		}

	}
	//关闭Connection
	public void closeConnection(Connection con) {
		try {
			if (con != null)
				con.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	//关闭PreparedStatement
	public void closePrepStmt(PreparedStatement ps) {
		try {
			if (ps != null)
				ps.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	//关闭ResultSet
	public void closeResultSet(ResultSet rs) {
		try {
			if (rs != null)
				rs.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

/** 处理根据ID找城市*/

package com.dao;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.db.DBManager;
import com.vo.City;

public class CityDao {
	public List<City> findByParentId(int parentId){
		String sqlString="select cityId,cityName,parentId,context from city where parentId="+parentId;
		DBManager dbManager=new DBManager();
		ResultSet rs=dbManager.query(sqlString);
		List<City> cities=new ArrayList<City>();
		try {
			while(rs.next()){
				cities.add(new City(rs.getInt("cityId"),rs.getString("cityName"),rs.getString("context")));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return cities;
	}
}


list4.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<title>无限下拉框联动</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">
		<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
		<script type="text/javascript"
			src="${pageContext.request.contextPath}/js/console.js"></script>
		<script type="text/javascript"
			src="${pageContext.request.contextPath}/js/loading.js"></script>
		<script type="text/javascript">
	var xmlHttpRequest = createXmlHttpRequest();

	var tagId2;
	//发送请求查找指定省份ID的市区
	function findShi(shengId,tagId) {
		tagId2=tagId;
		var isDelete=false;
		var sons=document.getElementById(tagId).childNodes;
		for ( var i = (sons.length-1); i >=0; i--) {
			if(sons[i].nodeName.toUpperCase()=="UL"){
				sons[i].parentNode.removeChild(sons[i]);
				isDelete=true;
			}
		}
		if(isDelete) return;
		var url = "${pageContext.request.contextPath}/getShiServlet2?shengId="
				+ shengId;
		xmlHttpRequest.open("GET",url,true);
		//关联好回调函数
		xmlHttpRequest.onreadystatechange = shiCallback;
		//清除缓存方法   加入请求头
		xmlHttpRequest.setRequestHeader("If-Modified-Since","0");
		//真正向服务器端发送数据
		xmlHttpRequest.send(null);
		return false;
	}

	//找到指定省份ID的市区后给市区的节点增加值
	function shiCallback() {
		if (xmlHttpRequest.readyState == 4) {
			debug("xmlHttpRequest.readyState==" + xmlHttpRequest.readyState);
			debug("xmlHttpRequest.status ==" + xmlHttpRequest.status);
			if (xmlHttpRequest.status == 200) {
				var s = xmlHttpRequest.responseText;
				debug("收到服务器回应==" + s);
				var shis = eval(s);
				if(shis.length==0){
					debug("--->shis.length==0");
					return;
				}
				var pli=document.getElementById(tagId2);
				var nul=document.createElement("ul");
				for ( var i = 0; i <shis.length; i++) {
					var nli=document.createElement("li");
					nli.id="tag"+shis[i].cityId;
					//注意转移双引号
					nli.innerHTML="<a href='#' onclick='return findShi("+shis[i].cityId+",\"tag"+shis[i].cityId+"\");'>"+shis[i].cityName+"</a>";
					nul.appendChild(nli);
				}
				pli.appendChild(nul);
			}
		}
	}
</script>
	</head>

	<body>
		<h1>
			无限下拉框联动
		</h1>
		<h3>
			您来自哪里?
		</h3>
		<hr>
		<ul>
			<c:forEach items="${requestScope.shengList}" var="sheng">
				<li id="tag${sheng.cityId}">
					<a href="#"
						onclick="return findShi(${sheng.cityId},'tag${sheng.cityId}');">
						${sheng.cityName}</a>
				</li>
			</c:forEach>
		</ul>
		<hr>
	</body>
</html>

package com.servlet;
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 org.json.JSONArray;
import com.dao.CityDao;
import com.vo.City;

public class getShiServlet2 extends HttpServlet {

	public void doGet(HttpServletRequest request,IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		int shengId=Integer.parseInt(request.getParameter("shengId"));
		CityDao cityDao=new CityDao();
		List<City> cities=cityDao.findByParentId(shengId);
		if(cities!=null){
			//声明 JSONArray
			JSONArray jsonArray=new JSONArray(cities);
			//生产字符串
			out.print(jsonArray.toString());
			System.out.print(jsonArray.toString());
		}
	}

	public void doPost(HttpServletRequest request,response);
	}

}

猜你在找的Ajax相关文章