Ajax局部刷新(Ajax入门)

知识了解

Ajax全称:Asynchronous Javascript And XML”(异步 JavaScript 和 XML),是指一种创建交互式网页应用的 网页开发技术。

Ajax 是一种用于创建快速动态网页的技术。

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

传统的网页(不使用 Ajax)如果需要更新内容,必须重载整个网页页面。

开发环境:
工具:idea
Tocmat版本:tocmat9
JDK版本:JDK11

局部刷新案例:创建一个JSP页面


```java
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>js调用ajax</title>
<style type="text/css">
	input{
		width:250px;
		height:25px;
	}
	#login{
		width:300px;
		height:50px;
		background-color:#FF3333;
		border:0px;
		cursor:pointer;
		color:white
	}
	.c1{
		font-size:24px;
		color:black;
		font-weight:bolder
	}
	.c2{
		font-size:14px;
		color:#666;
	}
	.c3{
		font-size:14px;
		color:red;
	}
</style>
</head>
<body style="text-align:center;">
			<input type="button" value="周一去干吗" flag="1" onclick="One()">
			<input type="button" value="周二去干吗" flag="2" onclick="Two()">
			<div style="..." id="div1">
			</div>
</body>
<script type="text/javascript">
	function One(){
		//1、创建 xmlhttpRequest对象
		var xmlhttp = new XMLHttpRequest();
		//2、规定请求的类型(请求类型GET/POST),URL 以及是否异步处理请求(true or false)。
		xmlhttp.open("GET","<%=basePath%>/ListCouseServlet?flag=1",true);
		//3、将请求发送到服务器。
		xmlhttp.send();
		//4、接收服务器端的响应(readyState=4表示请求已完成且响应已就绪    status=200表示请求响应一切正常)
		xmlhttp.onreadystatechange=function(){
			if (xmlhttp.readyState==4 && xmlhttp.status==200){
				//responseText:表示的是服务器返回给ajax的数据
		    	document.getElementById("div1").innerHTML=xmlhttp.responseText;
		    }
		}
	}

	function Two(){
		var xmlhttp=new XMLHttpRequest();
		xmlhttp.open("GET","<%=basePath%>/AjaxServlet?flag=2",true);
		xmlhttp.send();
		xmlhttp.onreadystatechange=function(){
			if(xmlhttp.readyState==400&&xmlhttp.status==200){
				document.getElementById("div1").innerHTML=xmlhttp.responseText;
			}
		}
	}
</script>
</html>

创建AjaxServlet


```java
@WebServlet("/AjaxServlet")
public class AjaxServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String flag=request.getParameter("flag");
        String ing="";
        if("1".equals(flag)){
           ing="爬山";
        }else if("2".equals(flag)){
            ing="打球";
        }
        response.getOutputStream().write(data.getBytes("utf-8"));
    }

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

}

发布了24 篇原创文章 · 获赞 5 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44519467/article/details/103359896