局部页面刷新,更新股票价格,经典案例
jsp页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript">
var xmlHttp;
function GetXmlHttpObject()
{
xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
function updateGoldPrice(){
GetXmlHttpObject();
if(xmlHttp){
var url="servlet/GoldPriceChange";
var data="city1=ld&city2=tw";
xmlHttp.open("post", url, true);
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //设置请求头
xmlHttp.onreadystatechange=deal;//设置处理返回数据的函数
xmlHttp.send(data);
}
}
function deal(){
if(xmlHttp.readyState==4&&xmlHttp.status==200){
var text = xmlHttp.responseText;
text=eval("("+text+")");
$('p1').innerText=text[0].price;
$('p2').innerText=text[1].price;
$('c1').innerText=text[0].price-1000;
$('c2').innerText=text[1].price-1000;
}
}
//使用定时器,每隔5秒发一次
window.setInterval("updateGoldPrice()", 5000);
function $(id){
return document.getElementById(id);
}
</script>
</head>
<body style="padding:200px;">
<table>
<tr><td>市场</td><td>最新价格</td><td>涨跌</td></tr>
<tr><td>伦敦</td><td id="p1">788.7</td><td id="c1">-211.3</td></tr>
<tr><td>台湾</td><td id="p2">854.0</td><td id="c2">-146.0</td></tr>
</table>
</body>
</html>
window.setInterval("函数名",time); 放在 script 中,表示系统每隔time 毫秒,便调用一次函数(函数名字符串是第一个参数)
servlet页面package com.haowan;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GoldPriceChange extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setHeader("Content-Type", "text/html;charset=utf-8");
PrintWriter out = response.getWriter();
String city1=request.getParameter("city1");
String city2=request.getParameter("city2");
int p1=(int)((Math.random()-0.5)*100)+1000;
int p2=(int)((Math.random()-0.5)*100)+1000;
String str="[{'price':"+p1+"},{'price':"+p2+"}]";
out.println(str);
out.flush();
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}