【JavaWeb】Ajax基础

Ajax介绍

Asynchronous JavaScript And XML(异步的JavaScript和XML);

Ajax可以在不刷新页面的前提下,进行页面局部更新;

Ajax不是新的技术,Ajax并不是W3C的标准;

Ajax的使用流程

  • 创建XmlHttpRequest对象
  • 发送Ajax请求
  • 处理服务器响应

处理服务器响应

  • xmlhttp.onreadystatechange()事件用于监听AJAX的执行过程
  • xmlhttp.readyState属性说明XMLHttpRequest当前状态
  • xmlhttp.status属性服务器响应状态码,200:成功、404:未找到...
readyState值 说明
readyState = 0 请求未初始化
readyState = 1 服务器连接已建立
readyState = 2 请求已被接收
readyState = 3 请求正在处理
readyState = 4 响应文本已被接收

实例代码

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>
		document.getElementById("btnLoad").onclick = function(){
			//1.创建XmlHttpRequest对象
			var xmlhttp;
			if(window.XMLHttpRequest){
				xmlhttp = new XMLHttpRequest(); //新版本浏览器
			}else{
				xmlhttp = new ActiveXobject("Microsoft.XMLHTTP"); //老版本浏览器
			}
			//2.发送Ajax请求
			xmlhttp.open("GET", "/ajax/content", true);//创建请求,true为异步执行
			xmlhttp.send(); //发送请求
			console.log(xmlhttp);
			//3.处理服务器响应
			xmlhttp.onreadystatechange = function(){
				//响应已被接收并且服务器处理成功
				if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
					var responseText = xmlhttp.responseText;
					document.getElementById("divContent").innerHTML = responseText;
				}
			}
		}
	</script>
</body>
</html>

ContentServlet.java

package demo;

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

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

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.getWriter().println("<b>I'm server content</b>");
	}

}

网页显示

posted @ 2019-08-03 16:02  星海|universe  阅读(220)  评论(0编辑  收藏  举报