AJAX的核心对象以及在级联中的简单应用实例

ajaxhe 2015-07-02

本篇文章主要是对学的AJAX做一个简单的总结和应用,实现一个城市选择的级联操作。

1,前台form表单实现城市的级联

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>级联下拉案例</title>
<script type="text/javascript" src="/selectHTML.js"></script>
</head>
<body>
	省份:
	<select name="province" id="province" onchange="loadCitys(this);">
	</select> &emsp; 
	城市:
	<select name="city" id="city">
		<option value='-1'>---请选择---</option>
	</select>
</body>
</html>

2,实现级联的js代码(主要是通过AJAX技术实现前后台数据交互)

function createAjax(){
	// 解决浏览器兼容性问题
        var ajax;
	try {
		ajax = new XMLHttpRequest();
	} catch (e) {
		ajax = new ActiveXObject("Mircosoft.XMLHTTP");
	}
	return ajax;
}

// 1.在页面加载完毕后,通过AJAX方式,动态加载省份信息
window.onload=function(){
	
	var provinceSel = document.getElementById("province");
	provinceSel.innerHTML="<option value='-1'>---请选择---</option>";
	
	// 创建核心对象
	var ajax = createAjax();
	// 添加状态监听
	ajax.onreadystatechange=function(){
		if(ajax.readyState==4 && ajax.status==200){
			var resp = ajax.responseText;
			//console.debug(resp);
			provinceSel.innerHTML+=resp;
		}
	};
	// 创建http请求
	ajax.open("get","/province");
	// 发送请求
	ajax.send();
};

function onchange(){
	// this >> provinceSel
	//[window.]loadCitys(this);
}

// 2.在选择某个省份后,及时加载这个省份对应的城市信息
function loadCitys(privinceSel){
	// 获取选中的省份ID
	var pid = privinceSel.value;
	
	// 获取城市select
	var citySel = document.getElementById("city");
	citySel.innerHTML="<option value='-1'>---请选择---</option>";
	
	// 创建核心对象
	var ajax = createAjax();
	// 添加状态监听
	ajax.onreadystatechange=function(){
		if(ajax.readyState==4 && ajax.status==200){
			var resp = ajax.responseText;
			//console.debug(resp);
			citySel.innerHTML += resp;
		}
	};
	// 创建http请求
	ajax.open("get","/loadCityByProvince?provinceId="+pid);
	// 发送请求
	ajax.send();
	
}

   

3,Servlet后台获取省级信息代码

package ajax.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ajax.domain.Province;

@WebServlet("/province")
public class ProvinceServlet extends HttpServlet {

	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		// 设置编码
		req.setCharacterEncoding("UTF-8");
		
		// 加载后台省份信息
		List<Province> provinceList = Province.getAllProvince();
		
		// 准备响应配置
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter writer = resp.getWriter();
		
		// 遍历每一个省份信息.返回<option value="1">四川</option>结构
		for (Province province : provinceList) {
			writer.write("<option value='"+province.getId()+"'>"+province.getName()+"</option>");
		}
		
	}
	
}

 使用json时要依赖的jar文件,在使用jquery的json时,没有引用该文件的时候容易报错。

4,Servlet获取市级城市信息

package ajax.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ajax.domain.City;
import ajax.domain.Province;

@WebServlet("/loadCityByProvince")
public class CityServlet extends HttpServlet {

	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		// 设置编码
		req.setCharacterEncoding("UTF-8");
		
		// 获取请求省份信息
		String provinceId  = req.getParameter("provinceId");
		
		// 根据省份信息,加载对应的城市信息
		List<City> citys = City.getCityByProvinceId(Long.parseLong(provinceId));
		
		// 准备响应配置
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter writer = resp.getWriter();
		
		// 遍历每一个省份信息.返回<option value="1">成都</option>结构
		for (City city : citys) {
			writer.write("<option value='"+city.getId()+"'>"+city.getName()+"</option>");
		}
		
	}
	
}

5,Servlet获取市级城市信息(这儿返回的数据为JSON格式)

package ajax.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONSerializer;

import ajax.domain.City;
import ajax.domain.Province;

@WebServlet("/loadCityByProvinceJSON")
public class CityJSONServlet extends HttpServlet {

	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		// 设置编码
		req.setCharacterEncoding("UTF-8");
		
		// 获取请求省份信息
		String provinceId  = req.getParameter("provinceId");
		
		// 根据省份信息,加载对应的城市信息
		List<City> citys = City.getCityByProvinceId(Long.parseLong(provinceId));
		
		// 准备响应配置
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter writer = resp.getWriter();
		
		// 遍历每一个省份信息.返回<option value="1">成都</option>结构
		writer.write(JSONSerializer.toJSON(citys).toString());
	}
	
}

web.xml配置文件

<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  version="3.0">

  <display-name>Welcome to Tomcat</display-name>
  <description>
     Welcome to Tomcat
  </description>

</web-app>

如果上述Servlet返回JSON数据,会依赖JSON相关jar包

ezmorph-1.0.6:使用json时要依赖的jar文件,在使用jquery的json时,没有引用该文件的时候容易报错。

json-lib-2.3-jdk15:JSON核心包

使用json-lib-2.2.3-jdk15.jar必要也要导入它的依赖包:

ezmorph-1.0.6.jar 
commons-lang 2.4 
commons-beanutils 1.7.0 
commons-collections 3.2 
commons-logging 1.1.1

相关推荐

libowen0 / 0评论 2019-06-27