使用Ajax实现页面的局部刷新
一.不依赖jquery时的用法:
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(event)
{
if(xhr.readyState==4&&xhr.status==200)
{
document.getElementById("line_count").innerHTML=xhr.responseText;
}
}
xhr.open('Get','Count',true);
xhr.send();
Count是web.xml中配置的,指向后端servlet文件,点击刷新执行该方法,局部修改line_count这个文本,
从而达到ajax局部刷新的目的
二.引入jquery.js,实现一个定时刷新在线人数,视频依旧播放的功能
index.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.text.*" %>
<%@ page import="java.util.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script src="js/jquery-3.3.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script>
function onQuery()
{
jQuery.ajax
(
{
method:"Get",
url:"Count",
success:function(data,textStatus,jqXHR)
{
$("#line_count").html(data);
},
error:function(jqXHR,textStatus,errorThrown)
{
alert(errorThrown);
}
}
);
}
function timedCount()
{
onQuery();
t=setTimeout("timedCount()",1000)
}
$(document).ready(function(){
timedCount();
});
</script>
</head>
<body>
<p> 当前共: <span id="line_count" sytle="color:red">0</span>在线人数</p>
<a href="javascript:onQuery()">刷新</a> <br/>
<video src="mp4/1.mp4" width=400 height=320 controls="controls"></video>
</body>
</html>
点击刷新按钮,会刷新line_count的文本,在html加载完毕会执行ready函数,启动一个自己实现的定时器
会一直定时刷新line_count的文本,jquery.timer.js也封装了一个timer,但这个例子中用的是用原生js自己实现的定时器
url:Count指向AjaxServlet.java
AjaxServlet.java——简单返回一个随机数:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
Random aRandom=new Random();
int count=aRandom.nextInt(1000);
PrintWriter out=response.getWriter();
out.write(String.valueOf(count));
}
效果: