学习Ajax

一、Ajax

1.1 简介

Ajax:(Asynchronous JavaScript And XML)指异步 JavaScript 及 XML

他不是一种新的编程语言,而是一种用于创建更好更快以及交互性更强的 Web 应用程序的技术,是基于JavaScript、XML、HTML、CSS新用法

Ajax指的是刷新局部页面的技术

1.2 应用场景
  • 搜索
  • 地图
  • 校验
  • 获取数据
1.3 交互模型

avatar

传统的Web交互方式

avatar

Ajax的交互方式

avatar

二、 Ajax使用详解

2.1 XMLHttpRequest对象

该对象用于在前台与服务器交换数据。意味着可以在不重新加载整个网页的情况下,对网页的进行局部更新

所有现代浏览器均支持 XMLHttpRequest 对象(IE5 和 IE6 使用 ActiveXObject)

//获取XMLHttpRequest对象
function getXMLHttpRequest() {
	var xmlHttp;
	if (window.XMLHttpRequest) {// 新浏览器
		xmlHttp = new XMLHttpRequest();
	}else if (window. ActiveXObject) {// IE6及以下浏览器
		xmlHttp = new ActiveXObject( "Microsoft.XMLHTTP");
	}
	return xmlHttp;
}
2.2 与服务器交换数据 open/send

如需将请求发送到服务器,我们使用 XMLHttpRequest 对象的 open() 和 send()

函数描述示例
open(method,url,async);初始化请求参数(请求方式,请求地址,是否异步)xmlhttp.open(“GET”,“url”,true);
send();发送请求xmlhttp.send();
//发送异步的Post请求
function sendAjaxPost() {
	var xmlHttp = getXMLHttpRequest();
	//初始化请求参数
	xmlHttp.open("POST","MyServlet",true);
	//post需要设置请求头
    xmlHttp.setRequestHeader(
        "Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
	//发送请求,携带数据
	xmlHttp.send("username=abc&password=123");
} 

//发送异步的Get请求
function sendAjaxGet() {
	var xmlHttp = getXMLHttpRequest();
	//初始化请求参数
	xmlHttp.open("GET","MyServlet?username=abc&password=123",true);
	//发送请求,携带数据
	xmlHttp.send();
} 
2.3 onreadystatechange事件

请求被发送到服务器时,我们需要执行一些基于响应的任务

函数描述
onreadystatechange每当 readyState 属性改变时,就会调用该函数。
属性描述
readyState存有 XMLHttpRequest 的状态。
从 0 到 4 发生变化:
0 - 请求未初始化服务器
1 - 连接已建立
2 - 请求已接收
3 - 请求处理中
4 - 请求已完成,且响应已就绪
status存有响应的状态。
200 - OK
404 - 未找到页面
//发送异步的Post请求
function sendAjaxPost() {
	
	var xmlHttp = getXMLHttpRequest();
	
	//每当readyState改变时,就会触发 onreadystatechange事件
	xmlHttp.onreadystatechange = function() {
		console.log(xmlHttp.readyState);//打印XMLHttpRequest的状态
		console.log(xmlHttp.status + "xx");//打印响应的状态
	}
	xmlHttp.open("POST","MyServlet",true);
    xmlHttp.setRequestHeader(
        "Content-Type","application/x-www-form-urlencoded;charset-UTF-8");
	xmlHttp.send("username=abc&password=123");
} 

三、实战案例

3.1 验证用户名

验证用户名的是否可以注册

<body>

	<h1>注册页面</h1>
	<form action="RegisterServlet" method="post">
		账号:<input name="username" type="text" placeholder="请输入账号..." 			
                  onblur="validateUsername(this)"/><font></font><br/>
		密码:<input name="password" type="password" placeholder="请输入密码..."/><br/>
		<input type="submit" value="注册"/>
	</form>
	<script type="text/javascript">
		var font = document.getElementsByTagName("font")[0];
		function validateUsername(obj) {	
			var xmlHttp = getXMLHttpRequest();
			xmlHttp.onreadystatechange = function() {
				if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
					//获取来自响应的信息
					var text = xmlHttp.responseText;
					if(text == "1"){
						font.color = "red";
						font.innerText = "抱歉,账号已被注册";
					}else if(text == "0"){
						font.color = "green";
						font.innerText = "恭喜,账号可用";
					}
				}
			}
			xmlHttp.open("POST","MyServlet",true);
		    xmlHttp.setRequestHeader(
                "Content-Type","application/x-www-form-urlencoded;charset-UTF-8");
			xmlHttp.send("username="+obj.value);
		} 
		function getXMLHttpRequest() {
			var xmlHttp;
			if (window.XMLHttpRequest) {// 新浏览器
				xmlHttp = new XMLHttpRequest();
			}else if (window. ActiveXObject) {// IE6及以下浏览器
				xmlHttp = new ActiveXObject( "Microsoft.XMLHTTP");
			}
			return xmlHttp;
		}
	</script>
</body>
public class MyServlet extends HttpServlet{
	private static final long serialVersionUID = 1L;
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		
		String username = request.getParameter("username");
		
		if(username.equals("hhy")){//已有此用户名
			response.getWriter().write("1");
		}else{//未有此用户名
			response.getWriter().write("0");
		}
	}
}	
3.2 级联效果

通过选择省从而关联出城市的数据

前端发送Ajax异步请求到服务器中获取对应的省市JSON数据,再在前端解析、适配到页面

  1. 添加数据库
  2. 导入数据库驱动包、Druid连接池
  3. 添加省、市实体类
public class Province{

	private int id;//id
	private String code;//省份编号
	private String name;//省份名

	public Province() {
	}
	public Province(int id, String code, String name) {
		this.id = id;
		this.code = code;
		this.name = name;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Override
	public String toString() {
		return "Province [id=" + id + ", code=" + code + ", name=" + name + "]";
	}
}
public class City{

	private int id;//id
	private String code;//城市编号
	private String name;//城市名
	private String parentCode;//所属省份编号
	public City() {
	}
	public City(int id, String code, String name, String parentCode) {
		this.id = id;
		this.code = code;
		this.name = name;
		this.parentCode = parentCode;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getParentCode() {
		return parentCode;
	}
	public void setParentCode(String parentCode) {
		this.parentCode = parentCode;
	}
	@Override
	public String toString() {
		return "City [id=" + id + ", code=" + code + ", name=" + name + ", parentCode=" + parentCode + "]";
	}
}
  1. 添加数据库工具类
public class DBUtil{

	private static DruidDataSource source;

	static{

		Properties properties = new Properties();
		try {	
            properties.load(DBUtil.class.getClassLoader()
                                .getResourceAsStream("dbconfig.properties"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		String username = properties.getProperty("username");
		String password = properties.getProperty("password");
		String url = properties.getProperty("url");
		String driver = properties.getProperty("driver");

		source = new DruidDataSource();
		source.setDriverClassName(driver);
		source.setUrl(url);
		source.setUsername(username);
		source.setPassword(password);
	}
	public static Connection getConnection() {
		try {
			return source.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	public static void close(Connection conn,Statement statement,ResultSet resultSet){
		if(resultSet != null){
			try {
				resultSet.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(statement != null){
			try {
				statement.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(conn != null){
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}
  1. 编写数据持久层
public class UserDao{

	//获取所有省份
	public List<Province> getProvinceList(){

		List<Province> provinceList = new ArrayList<>();

		Connection conn = null;
		PreparedStatement statement = null;
		ResultSet resultSet = null;
		try {
			conn = DBUtil.getConnection();
			String sql = "select * from provinces where parent_code=?";
			statement = conn.prepareStatement(sql);
			statement.setString(1, "01");
			resultSet = statement.executeQuery();
			while (resultSet.next()) {
				int id = resultSet.getInt("id");
				String code = resultSet.getString("code");
				String name = resultSet.getString("name");
				Province province = new Province(id, code, name);
				provinceList.add(province);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(conn, statement, resultSet);
		}
		return provinceList;
	}

	//获取省份对应城市
	public List<City> getCityList(String parentCode){
		List<City> cityList = new ArrayList<>();

		Connection conn = null;
		PreparedStatement statement = null;
		ResultSet resultSet = null;
		try {
			conn = DBUtil.getConnection();
			String sql = "select * from provinces where parent_code=?";
			statement = conn.prepareStatement(sql);
			statement.setString(1, parentCode);
			resultSet = statement.executeQuery();
			while (resultSet.next()) {
				int id = resultSet.getInt("id");
				String code = resultSet.getString("code");
				String name = resultSet.getString("name");
				City city = new City(id, code, name, parentCode);
				cityList.add(city);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(conn, statement, resultSet);
		}
		return cityList;
	}
}
  1. 编写Servlet
public class UserServlet extends HttpServlet{
	private static final long serialVersionUID = 1L;
	private UserDao useDao = new UserDao();

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");

		String action = request.getParameter("action");
		String parentCode = request.getParameter("parentCode");
		
		if(action.equals("getProvinceList")){
			
			List<Province> provinceList = useDao.getProvinceList();
			String jsonStr = JSON.toJSONString(provinceList);
			response.getWriter().write(jsonStr);
			
		}else if(action.equals("getCityList")){
			
			List<City> cityList = useDao.getCityList(parentCode);
			String jsonStr = JSON.toJSONString(cityList);
			response.getWriter().write(jsonStr);
		}
	}
}
  1. 编写前端页面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

	<h1>省市联动</h1>
	<select id="province"></select><select id="city"></select><script type="text/javascript">
		var province = document.getElementById("province");
		var city = document.getElementById("city");
		
		//获取省列表的函数
		function getProvinceList() {
			var xmlHttp = getXMLHttpRequest();
			xmlHttp.onreadystatechange = function() {
				if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
					
					var text = xmlHttp.responseText;
					//JSON解析
					var provinceList = eval(text);
					//控制是否添加城市
					var bool = true;
					//循环添加省份
					for(var i = 0;i<provinceList.length;i++){
						var option = document.createElement("option");
						option.innerText = provinceList[i].name;
						option.value = provinceList[i].code;
						province.add(option);
						if(bool){//第一个省就添加对应的市
							getCityList(provinceList[i].code);
							bool = false;
						}
					}
					
				}
			}
			xmlHttp.open("GET","UserServlet?action=getProvinceList",true);
			xmlHttp.send();
		}
		
		//获取市列表的函数
		function getCityList(parentCode) {
			var xmlHttp = getXMLHttpRequest();
			xmlHttp.onreadystatechange = function() {
				if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
					var text = xmlHttp.responseText;
					//JSON解析
					var cityList = eval(text);
					//先把城市列表置空
					city.length = 0;
					//循环添加城市
					for(var i = 0;i<cityList.length;i++){
						var option = document.createElement("option");
						option.innerText = cityList[i].name;
						option.value = cityList[i].code;
						city.add(option);
					}

				}
			}
			xmlHttp.open("POST","UserServlet",true);
		    xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset-UTF-8");
			xmlHttp.send("action=getCityList&parentCode=" + parentCode);
		}
		
		//一开始就调用获取省列表的函数
		getProvinceList();
		
		//给省绑定改变时间
		province.onchange = function (){
			getCityList(this.value);
		} 
		
		function getXMLHttpRequest() {
			var xmlHttp;
			if (window.XMLHttpRequest) {// 新浏览器
				xmlHttp = new XMLHttpRequest();
			}else if (window. ActiveXObject) {// IE6及以下浏览器
				xmlHttp = new ActiveXObject( "Microsoft.XMLHTTP");
			}
			return xmlHttp;
		}
	</script>

</body>
</html>

四、总结

使用Ajax+JSON,前后端分离,大大提高了工作效率和用户体验

  • 7
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值