Ajax和Json的使用

一.实现时钟功能实例
1.添加 spring-webmvc 3.2.8版本
添加 jackson-core 2.2.3版本
添加 jackson-annotations 2.2.3版本
添加 jackson-databind 2.2.3版本

在webapp下添加js文件夹里添加jquery.min.js文件


2.web.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	version="2.5">
	<display-name>DAY10-03-Ajax-Timer</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
	<servlet>
		<servlet-name>SpringMVC</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:applicationContext.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>SpringMVC</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>
</web-app>

3.resources下applicationContext.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util"
	xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">

	<context:component-scan base-package="cn.tedu.spring" />
	<mvc:annotation-driven>
		<mvc:message-converters>
			<bean class="org.springframework.http.converter.StringHttpMessageConverter">
				<property name="supportedMediaTypes">
					<list>
						<value>text/html;charset=utf-8</value>
						<value>application/json;charset=utf-8</value>
						<value>*/*;charset=utf-8</value>
					</list>
				</property>
			</bean>
		</mvc:message-converters>
	</mvc:annotation-driven>
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>

</beans>

4.响应结果数据类

package cn.tedu.spring.bean;

public class ResponseResult {
	private int state;
	private String message;
	private Object data;
	public ResponseResult() {
		super();
	}
	public ResponseResult(int state) {
		super();
		this.state = state;
	}
	public ResponseResult(int state, String message) {
		super();
		this.state = state;
		this.message = message;
	}
	public ResponseResult(int state, Object data) {
		super();
		this.state = state;
		this.data = data;
	}
	public ResponseResult(int state, String message, Object data) {
		super();
		this.state = state;
		this.message = message;
		this.data = data;
	}
	public int getState() {
		return state;
	}
	public void setState(int state) {
		this.state = state;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	public Object getData() {
		return data;
	}
	public void setData(Object data) {
		this.data = data;
	}
	
}

5.时间控制类

package cn.tedu.spring.controller;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import cn.tedu.spring.bean.ResponseResult;

@Controller
public class TimeController {
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
	ObjectMapper om = new ObjectMapper();
	private static Date date = new Date();
	ResponseResult result = new ResponseResult();
	
	@RequestMapping("showTime.do")
	@ResponseBody
	public String showTime() {
		date.setTime(System.currentTimeMillis());
		String timeString = sdf.format(date);
		
		result.setState(1);
		result.setData(timeString);
		
		String jsonString = null;
		try {
			jsonString = om.writeValueAsString(result);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return jsonString;
	}
}

6.webapp下index.html文件

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ajax Timer</title>
<script type="text/javascript">
function $(id) {
	return document.getElementById(id);
}

function getXMLHttpRequest() {
	var xmlhttp = null;
	if (window.XMLHttpRequest) {
		xmlhttp = new XMLHttpRequest();
	} else {
		xmlhttp = new ActiveXObject("Microsoft.XMLHttp");
	}
	return xmlhttp;
}
function showTime(){
	var xmlhttp = getXMLHttpRequest();
	var url = "showTime.do";
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
			var jsonText = xmlhttp.responseText;
			var jsonObject = JSON.parse(jsonText);
			if (jsonObject.state == 1) {
				var timeString = jsonObject.data;
				$("timer").innerHTML = timeString;
			}
		}
	};
	xmlhttp.open("GET", url, true);
	xmlhttp.send();
	
	setTimeout("showTime()", 1000);
}
</script>
</head>
<body>
	<span id="timer"></span>
	<input type="button" value="START" onclick="showTime()" />
</body>
</html>

二.下拉选地区二级联动菜单实例
1.添加 spring-webmvc 3.2.8版本
添加 jackson-core 2.2.3版本
添加 jackson-annotations 2.2.3版本
添加 jackson-databind 2.2.3版本

2.web.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	version="2.5">
	<display-name>DAY11-01-Ajax-Menu</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
	<servlet>
		<servlet-name>SpringMVC</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:applicationContext.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>SpringMVC</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>
</web-app>

3.resources下applicationContext.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util"
	xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">

	<context:component-scan base-package="cn.tedu.spring" />
	<mvc:annotation-driven>
		<mvc:message-converters>
			<bean class="org.springframework.http.converter.StringHttpMessageConverter">
				<property name="supportedMediaTypes">
					<list>
						<value>text/html;charset=utf-8</value>
						<value>application/json;charset=utf-8</value>
						<value>*/*;charset=utf-8</value>
					</list>
				</property>
			</bean>
		</mvc:message-converters>
	</mvc:annotation-driven>
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>

</beans>

4.城市类

package cn.tedu.spring.bean;

public class City {
	private int id;
	private String name;
	public City() {
		super();
	}
	public City(int id, String name) {
		super();
		this.id = id;
		this.name = name;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	
}

5.响应结果数据类

package cn.tedu.spring.bean;

public class ResponseResult {
	private int state;
	private String message;
	private Object data;
	public ResponseResult() {
		super();
	}
	public ResponseResult(int state) {
		super();
		this.state = state;
	}
	public ResponseResult(int state, String message) {
		super();
		this.state = state;
		this.message = message;
	}
	public ResponseResult(int state, Object data) {
		super();
		this.state = state;
		this.data = data;
	}
	public ResponseResult(int state, String message, Object data) {
		super();
		this.state = state;
		this.message = message;
		this.data = data;
	}
	public int getState() {
		return state;
	}
	public void setState(int state) {
		this.state = state;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	public Object getData() {
		return data;
	}
	public void setData(Object data) {
		this.data = data;
	}
	
}

6.城市控制类

package cn.tedu.spring.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import cn.tedu.spring.bean.City;
import cn.tedu.spring.bean.ResponseResult;

@Controller
public class CityController {
	
	@RequestMapping("getCities.do")
	@ResponseBody
	public String getCities(int provinceId) {
		//城市列表
		List<City> cities = new ArrayList<City>();
		//根据参数进行判断
		switch (provinceId) {
		case 1:
			cities.add(new City(1,"广州"));
			cities.add(new City(2,"深圳"));
			cities.add(new City(3,"珠海"));
			break;

		case 2:
			cities.add(new City(4,"石家庄"));
			cities.add(new City(5,"保定"));
			cities.add(new City(6,"秦皇岛"));
			break;
		default:
			break;
		}
		//封装ResponseResult
		ResponseResult rr = new ResponseResult();
		rr.setState(1);
		rr.setData(cities);
		//将结果转换为JSON字符串
		String jsonString = null;
		try {
			ObjectMapper om = new ObjectMapper();
			jsonString = om.writeValueAsString(rr);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return jsonString;
	}
	
}

7.webapp下index.html文件

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ajax -- 二级联动菜单</title>
<script type="text/javascript">
	function $(id){
		return document.getElementById(id);
	}
	
	function getXMLHttpRequest(){
		var xmlhttp = null;
		if(window.XMLHttpRequest){
			//适用于IE 7+、Chrome、Firefox、Safari、Opera......
			xmlhttp = new XMLHttpRequest();
		}else{
			//适用于IE 5、IE 6
			xmlhttp = new ActiveXObject("Microsoft.XMLHttp");
		}
		return xmlhttp;
	}

	function getCities(provinceId){
		//清空城市列表
		while($("cities").firstChild){
			$("cities").removeChild($("cities").firstChild);
		}
		//判断provinceId是否有效
		if(provinceId == 0){
			return;
		}
		//获取XMLHttpRequest
		var xmlhttp = getXMLHttpRequest();
		//设计响应函数
		xmlhttp.onreadystatechange = function(){
			if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
				//获取响应的正文文本
				var text = xmlhttp.responseText;
				//将响应的正文文本转换为JSON对象
				var jsonObject = JSON.parse(text);
				//判断JSON对象中的state是否正确
				if(jsonObject.state == 1){
					//遍历JSON对象中的data对应的数组
					for(var i = 0; i<jsonObject.data.length;i++){
						//将数组中的每个数据设计为一个个<option>
						var opt = document.createElement("option");
						//<option value="1">广东省</option>
						//<option></option>
						//"data":[
						//			{"id":1,"name":"广州"}
						//			{"id":2,"name":"深圳"}
						//			{"id":3,"name":"珠海"}
						// ]
						opt.value = jsonObject.data[i].id;
						console.log(opt.value);
						opt.innerHTML = jsonObject.data[i].name;
						console.log(opt.innerHTML);
						//将<option>添加到“城市”列表中
						$("cities").appendChild(opt);
					}
				}
			}
		}
		//发出请求
		var url = "getCities.do?provinceId="+provinceId;
		xmlhttp.open("GET",url,true);
		xmlhttp.send();
	}
</script>
</head>
<body>
	<select style="width: 120px;" onchange="getCities(this.value)">
		<option value="0" selected>----- 请选择 -----</option>
		<option value="1">广东省</option>
		<option value="2">河北省</option>
	</select>
	
	<select style="width: 120px;" id="cities">
		
	</select>
</body>
</html>

8.webapp下load.html文件

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JQuery Ajax -- load</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
	function loadContent(){
		$("#content").load("getCities.do","provinceId=1");
	}
</script>
</head>
<body>
	<div id="content" style="border:1px solid #999; width: 300px; height: 200px;">
	</div>
	<p>
		<input type="button" value="使用jQuery提交AJAX请求" onclick="loadContent()" />
	</p>
</body>
</html>

9.webapp下jquery_ajax.html文件

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ajax -- 二级联动菜单</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
	//为了便于可能存在的事件绑定,
	//凡是与事件相关的函数,
	//能不定义参数就不要定义参数,
	//对于那些动态的,可能变化的值,
	//推荐在函数内部去动态获取
	function getCities(pid){
		//清空城市的下拉列表
		$("#cities").empty();//相当于innerHTML=""
		
		//获取当前选中的“省份”的value
		var id = $("#provinces").val();
		
		//如果获取到的是0,则不处理
		if(pid == 0){
			return;
		}
		
		//发出请求并处理响应结果
		$.ajax({
			"url":"getCities.do",
			"type":"GET",
			"data":"provinceId=" + id,
			"dataType":"json",
			"success":function(obj){
				//判断JSON对象中的state
				if(obj.state == 1){
					for(var i=0;i<obj.data.length;i++){
						//创建<option>的HTML代码
						var op = "<option value="+obj.data[i].id+">"+obj.data[i].name+"</option>";
						//将<option>添加到“城市”下拉菜单
						$("#cities").append(op);
					}
				}
			}
		});
	}
</script>
</head>
<body>
	<h3>jQuery Ajax -- 二级联动菜单</h3>

	<select id="provinces" style="width: 120px;" onchange="getCities(this.value)">
		<option value="0" selected>----- 请选择 -----</option>
		<option value="1">广东省</option>
		<option value="2">河北省</option>
	</select>
	
	<select style="width: 120px;" id="cities">
		
	</select>
</body>
</html>




猜你喜欢

转载自blog.csdn.net/linsa_pursuer/article/details/79117914