首页 > 代码库 > 使用JavaScript动态刷新页面局部内容
使用JavaScript动态刷新页面局部内容
html页面:
<%@page contentType="text/html; charset=Shift_JIS"%>
<html>
<head>
<title>equipment</title>
<script type="text/javascript" language="javascript">
var req;
//initialize request.
function initRequest(url) {
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
req.open("GET", url, true);
}
//start work
function work() {
//target servlet
var url = "equipmentservlet";
//initialize request
initRequest(url);
// set callback function
req.onreadystatechange = displayStatus;
//do
req.send(null);
}
function displayStatus() {
if (req.readyState == 4) {
if (req.status == 200) {
var i = 0;
var str = req.responseText;
if (str == null || str.length != 7) {
} else {
for (i = 0; i < 7; i++) {
var status = str.charAt(i);
setStatus(i, status);
}
}
setTimeout("work()", 6000);
}
}
}
function setStatus(i, status) {
var labelName = ‘equipment_‘ + i;
var idiv = window.document.getElementById(labelName);
if (status == ‘1‘) {
idiv.innerHTML = ‘<font color="red">error</font>‘;
}
if (status == ‘0‘) {
idiv.innerHTML = ‘<font color="black">good</font>‘;
}
}
</script>
</head>
<body bgcolor="#ffffff" onl oad="work();">
<h1>
設備
<br>
<table border="1">
<tr>
<td>
設備 0
</td>
<td>
<div id="equipment_0"></div>
</td>
</tr>
<tr>
<td>
設備 1
</td>
<td>
<div id="equipment_1"></div>
</td>
</tr>
<tr>
<td>
設備 2
</td>
<td>
<div id="equipment_2"></div>
</td>
</tr>
<tr>
<td>
設備 3
</td>
<td>
<div id="equipment_3"></div>
</td>
</tr>
<tr>
<td>
設備 4
</td>
<td>
<div id="equipment_4"></div>
</td>
</tr>
<tr>
<td>
設備 5
</td>
<td>
<div id="equipment_5"></div>
</td>
</tr>
<tr>
<td>
設備 6
</td>
<td>
<div id="equipment_6"></div>
</td>
</tr>
</table>
</h1>
</body>
</html>
servlet主要部分:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("begin");
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
PrintWriter pw = response.getWriter();
StringBuffer buf = new StringBuffer();
for(int i = 0; i < 7; i++)
{
int status = (int)(Math.random() * 2);
buf.append("" + status );
}
System.out.println("message:\n" + buf.toString() + "\n");
pw.write(buf.toString());
pw.flush();
System.out.println("end");
}
web.xml配置:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>equipment</display-name>
<servlet>
<servlet-name>equipmentservlet</servlet-name>
<servlet-class>dynamicflush.EquipmentServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>equipmentservlet</servlet-name>
<url-pattern>/equipmentservlet</url-pattern>
</servlet-mapping>
</web-app>
摘自:http://blog.csdn.net/amose/archive/2005/06/07/389793.aspx
使用JavaScript动态刷新页面局部内容