Ajax的使用

AJAX 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。

AJAX使用流程

  • 创建XmlHttpRequest对象
            var xmlhttp;
			if(window.XMLHttpRequest){
				//如果是新版本浏览器
				xmlhttp=new XMLHttpRequest();
			}else{
				//如果是古老的版本:IE5,IE6...
				xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
  • 发送Ajax请求
  1. 创建请求:xmlhttp.open();
  2. 发送请求:xmlhttp.send();
xmlhttp.open("GET","/ajax/content",true);//第三个参数设置同步或异步
xmlhttp.send();
  • 处理服务器响应
  1. xmlhttp.onreadystatechange() 事件用于监听AJAX的执行过程
  2. xmlhttp.readyState属性说明XMLHttpRequest当前状态
  3. xmlhttp.status属性服务器响应状态码

xmlhttp.onreadystatechange=function(){
				//响应已被接收且服务器处理成功时才执行
				if(xmlhttp.readyState==4&&xmlhttp.status==200){
					//获取响应体文本
					var responseText=xmlhttp.responseText;
					//对服务器结果进行处理
					document.getElementById("divContent").innerHTML=responseText;
				}
			}

 ContentServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().println("<b>hello,I'am content</b>");
	}

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<input id="btnLoad" type="button" value="加载">
	<div id="divContent"></div>
	
	<script type="text/javascript">
		document.getElementById("btnLoad").onclick=function(){
			//1,创建XmlHttpRequest对象
			var xmlhttp;
			if(window.XMLHttpRequest){
				//如果是新版本浏览器
				xmlhttp=new XMLHttpRequest();
			}else{
				//如果是古老的版本:IE5,IE6...
				xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
			//2,发送Ajax请求
			xmlhttp.open("GET","/ajax/content",true);//第三个参数设置同步或异步
			xmlhttp.send();
			//3,处理服务器响应
			xmlhttp.onreadystatechange=function(){
				//响应已被接收且服务器处理成功时才执行
				if(xmlhttp.readyState==4&&xmlhttp.status==200){
					//获取响应体文本
					var responseText=xmlhttp.responseText;
					//对服务器结果进行处理
					document.getElementById("divContent").innerHTML=responseText;
				}
			}

		}
	</script>
</body>
</html>

    


Ajax实现新闻列表

News.java

package com.ulikeme.ajax;

public class News {
	private String title;
	private String date;
	private String source;
	private String content;
	public News() {
		
	}
	
	public News(String title, String date, String source, String content) {
		super();
		this.title = title;
		this.date = date;
		this.source = source;
		this.content = content;
	}


	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getDate() {
		return date;
	}
	public void setDate(String date) {
		this.date = date;
	}
	public String getSource() {
		return source;
	}
	public void setSource(String source) {
		this.source = source;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	
}

NewsListServlet.java


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		List list=new ArrayList();
		list.add(new News("天气预报1","2021-01-21","北京","会下雨...."));
		list.add(new News("天气预报2","2021-01-22","北京","会下雨...."));
		list.add(new News("天气预报3","2021-01-23","北京","会下雨...."));
		list.add(new News("天气预报4","2021-01-24","北京","会下雨...."));
		list.add(new News("天气预报5","2021-01-25","北京","会下雨...."));
		String json= JSON.toJSONString(list);
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().println(json);
	}

news.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<div id="container"></div>

	<script type="text/javascript">
		//1,创建XmlHttpRequest对象
		var xmlhttp;
		if (window.XMLHttpRequest) {
			//如果是新版本浏览器
			xmlhttp = new XMLHttpRequest();
		} else {
			//如果是古老的版本:IE5,IE6...
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		//2,发送Ajax请求
		xmlhttp.open("GET", "/ajax/news_list", true);//第三个参数设置同步或异步,true是异步,false是同步
		xmlhttp.send();
		//3,处理服务器响应
		xmlhttp.onreadystatechange = function() {
			//响应已被接收且服务器处理成功时才执行
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				//获取响应体文本
				var responseText = xmlhttp.responseText;
				//对服务器结果进行处理
				var json = JSON.parse(responseText);
				var html = "";
				for (var i = 0; i < json.length; i++) {
					var news = json[i];
					html = html + "<h1>" + news.title + "</h1>";
					html = html + "<h2>" + news.date + "</h1>"
					html = html + "<h3>" + news.source + "</h1>"
					html = html + "<h4>" + news.content + "</h1>"
					html = html + "<hr><br>"
				}
				document.getElementById("container").innerHTML = html;
			}
		}
	</script>

</body>
</html>

效果:


Ajax的同步和异步 

同步请求即是当前发出请求后,浏览器什么都不能做,必须得等到请求完成返回数据之后,才会执行后续的代码,相当于是排队,前一个人办理完自己的事务,下一个人才能接着办。

 异步请求就当发出请求的同时,浏览器可以继续做任何事,Ajax发送请求并不会影响页面的加载与用户的操作,相当于是在两条线上,各走各的,互不影响。

JQuery对Ajax的支持

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
	<script type="text/javascript">
		$(function(){
			$.ajax({
				"url":"/ajax/news_list",
				"type":"get",
				"data":{"id":"1","name":"jack"},
				"dataType":"json",
				"success":function(json){
					console.log(json);
					for(var i=0;i<json.length;i++){
						$(".container").append("<h1>"+json[i].title+"</h1>");
					},
                 "error":function(xmlhttp,errorText){
					if(xmlhttp.status=="405"){
						alert("无效的请求方式");
					}else if(xmlhttp.status=="404"){
						alert("未找到url资源");
					}else if(xmlhttp.status=="500"){
						alert("服务器内部错误");
					}else{
						alert("产生异常!");
					}
				  }
				}
				
			})
		})
		
	</script>
</head>
<body>
	<div class="container"></div>
</body>
</html>


实现二级联动菜单

Channel.java

package com.ulikeme.ajax;

public class Channel {
	private String code;
	private String name;
	public Channel() {
		
	}
	public Channel(String code, String name) {
		super();
		this.code = code;
		this.name = name;
	}
	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;
	}
	
}

ChannelServlet.java



/**
 * Servlet implementation class ChannelServlet
 */
@WebServlet("/channel")
public class ChannelServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ChannelServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String level=request.getParameter("level");
		String parent=request.getParameter("parent");
		List<Channel> chlist=new ArrayList<Channel>();
		if(level.equals("1")) { //一级频道
			chlist.add(new Channel("php","世界上最好的语言"));
			chlist.add(new Channel("java","世界最热门语言"));
		}else if(level.equals("2")) {
			if(parent.equals("php")) {
				chlist.add(new Channel("php入门","php编程入门"));
				chlist.add(new Channel("php基础","php编程基础"));
				chlist.add(new Channel("php高级","php高级编程"));
			}else if(parent.equals("java")) {
				chlist.add(new Channel("java入门","java编程入门"));
				chlist.add(new Channel("java基础","java编程基础"));
				chlist.add(new Channel("java高级","java高级编程"));
			}
		}
		
		String json=JSON.toJSONString(chlist);
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().println(json);
	}


}

cascade_meun.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
	$(function() {
		$.ajax({
			"url" : "/ajax/channel",
			"type" : "get",
			"data" : {
				"level" : "1"
			},
			"dataType" : "json",
			"success" : function(json) {
				for (var i = 0; i < json.length; i++) {
					$("#lv1").append(
							"<option value='"+json[i].code+"'>" + json[i].name
									+ "</option>");
				}
			}

		})
	})
	//-------联动二级频道数据-----------------------------
	$(function(){
		$("#lv1").on("change",function(){
			var parent=$(this).val();
			$.ajax({
				"url" : "/ajax/channel",
				"type" : "get",
				"data" : {
					"level" : "2",
					"parent":parent
				},
				"dataType" : "json",
				"success" : function(json) {
					$("#lv2>option").remove();
					for (var i = 0; i < json.length; i++) {
						$("#lv2").append(
								"<option value='"+json[i].code+"'>" + json[i].name
										+ "</option>");
					}
				}

			})
		})
	})
</script>
</head>
<body>
	<select id="lv1" style="width: 200px; height: 30px">
		<option selected="selected">请选择</option>
	</select>

	<select id="lv2" style="width: 200px; height: 30px">
		<option selected="selected">请选择</option>
	</select>

</body>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值