Ajax_servelt 实现页面自动刷新

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();

  //针对IE5IE5.5IE6

  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 οnlοad="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.运行效果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值