有时候在写网页时需要保证数据每隔一段时间进行更新,但又不能让整个页面刷新,所以可以定时的调用ajax帮我们完成数据的更新。
效果图
jsp页面代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ajax Test</title>
<script src="js/jquery-3.3.1.js"></script>
<script src="js/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
var getting = {
url : "${pageContext.request.contextPath}/Test1", //后台查询验证的方法
dataTpye : "json",
data : {
},
type : "post",
success : function(msg) {
$("#info").append(msg+'</br>');
},
error:function(){ //请求失败的回调方法
alert("请求失败,请重试");
}
};
window.setInterval(function(){$.ajax(getting)},3000); //每三秒调用一次ajax
</script>
</head>
<body>
<div id="info">
</div>
</body>
</html>
servlet中返回的是一个字符串和当前时间的拼接
package cn.ch.action;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Test1
*/
public class Test1 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Test1() {
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
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
response.getWriter().print("this is a test massage"+df.format(new Date()));
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}