ajax+servlet实现自动刷新

http://www.java3z.com/cwbwebhome/article/article8/81381.html?id=3866

1.实现思路

在ajax回调函数中用方法setTimeout("load()", 1000),这样就会每隔1秒自动去请求新的信息,实现自动刷新的功能。

2.实例

(1)index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
	String path = request.getContextPath();
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<title>ajax+servlet实现自动刷新页面</title>
 <mce:script type="text/javascript"><!--
  function $(id){
      return document.getElementById(id);
  }
  var xmlHttp;
  //根据浏览器创建xmlHttpRequest对象
  function getXmlHttpRequest() {
  //针对FireFox,Mozillar,Opera,Safari,IE7,IE8
  if(window.XMLHttpRequest) 
      return new XMLHttpRequest();
  //针对IE5,IE5.5,IE6
  else if (window.ActiveXObject){  
       //两个可以用于创建XMLHTTPRequest对象的控件名称,保存在一个JS数组中。
       var activexName = ["MSXML2.XMLHTTP","Microsoft.XMLHTTP"];
       for(var i = 0; i<activexName.length; i++){
           //取出一个控件名进行创建,如果成功就终止循环
           try{
              return new ActiveXObject(activexName[i]);
              break;
           }catch(e){
           return null;
           }
       }
       }       
  }
  function load(){
           xmlHttp=getXmlHttpRequest();
             var url="servlet/GetMp3Info";
           // 注册回调函数,只写函数名,不能写括号,写括号表示调用函数
           xmlHttp.onreadystatechange = getResult;
           // 确定发送请求的方式和URL以及是否同步执行下段代码
           xmlHttp.open("GET", url, true);
           //发送数据,开始和服务器进行交互
           xmlHttp.send(null);
  }
  //回调函数
  function getResult(){
      if (xmlHttp.readyState == 4) { // 判断对象状态
            if (xmlHttp.status == 200) { // 信息已经成功返回,开始处理信息
         var text=xmlHttp.responseXML;
         var name=text.getElementsByTagName("name")[0].firstChild.nodeValue;
         var number=text.getElementsByTagName("number")[0].firstChild.nodeValue;
         $("name").innerHTML=name;
         $("number").innerHTML=number;
         setTimeout("load()", 1000);
        } else { 
                  alert("请求的出错啦!");
       }
  }
  }
  
// --></mce:script>
</head>
	<body onload="load()">
		<form>
			<table>
				<thead>
					<tr>
						<th colspan="2">
													</th>
					</tr>
				</thead>
				<tbody>
					<tr>
						<td>名称</td>
						<td id="name"></td>
					</tr>
					<tr>
					    <td>数量</td>
					    <td id="number"></td>
					</tr>
				</tbody>
			</table>
		</form>
	</body>
</html>
        

 

(2)GetMp3Info.java(servlet)

 

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GetMp3Info extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/xml;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		response.setHeader("Cache-Control","no-cache");
		String name[]={"索尼","清华紫光","纽曼","步步高"};
        String str="";
        str+="<mp3>";
        str+="<name>"+name[new Random().nextInt(name.length)]+"</name>";
        str+="<number>"+new Random().nextInt(1000)+"</number>";
        str+="</mp3>";
        System.out.println("str="+str);
        response.getWriter().write(str);
        response.getWriter().flush();
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request,response);
	}
}
 

(3)web.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>GetMp3Info</servlet-name>
    <servlet-class>GetMp3Info</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>GetMp3Info</servlet-name>
    <url-pattern>/servlet/GetMp3Info</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
 

3.运行效果

 

 

 

 

猜你喜欢

转载自andrewstz.iteye.com/blog/1668377
今日推荐