以下代码分ajax.asp和getPart.asp两个文件,一定放在同一目录下。ajax.asp文件用于显示getPart.asp中的内容,getPart.asp可以自己使用普通的网页文件,当这个文件内容修改时,ajax.asp文件显示的内容也跟着改变。示例getPart.asp中加入了数据库内容,需要测试者自己连接现成的数据库,这里没有附带。getPart.asp中,数据库提取的内容,使用了escape函数,请一定不能删除,删除了会显示乱码。ajax.asp中的setInterval("getPart('getPart.asp')",1000)
语句中,使用了1000ms刷新,可以修改这个数字,调节刷新频率,如果服务器性能比较差时,建议把这个数字调整得大一些。
以下代码,在xp+IIS5.1环境下测试成功。
ajax.asp源代码(请删除""右侧和左侧的空格)
< %@LANGUAGE="VBSCRIPT"
CODEPAGE="936"% >
< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>
< html xmlns="http://www.w3.org/1999/xhtml"
>
< head >
< meta http-equiv="Content-Type" content="text/html;
charset=utf-8" / >
< meta name="viewport" content="width=100%; initial-scale=1.0;
maximum-scale=1.0; user-scalable=0;" / >
< title >AJAX局部刷新< /title >
< script type="text/javascript" >
< !--
//建立xmlhttpRequest对象
var xmlhttp;
try{
xmlhttp= new ActiveXObject('Msxml2.XMLHTTP');
}catch(e){
try{
xmlhttp= new ActiveXObject('Microsoft.XMLHTTP');
}catch(e){
try{
xmlhttp= new XMLHttPRequest();
}catch(e){}
}
}
function getPart(url){
xmlhttp.open("get",url,true);
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4)
{
if(xmlhttp.status == 200)
{
if(xmlhttp.responseText!=""){
document.getElementByIdx_x("partdiv").innerHTML =
(xmlhttp.responseText);
}
}
else{
document.getElementByIdx_x("partdiv").innerHTML = "数据载入出错";
}
}
}
xmlhttp.setRequestHeader("If-Modified-Since","0");
xmlhttp.send(null);
}
setInterval("getPart('getPart.asp')",1000)
//-->
< /script >
< /head >
< body >
< div id="partdiv" >< /div >< !--局部刷新数据的容器--
>
< /body >
< /html >
getPart.asp源代码(请删除""右侧和左侧的空格)
以下程序为连接数据库程序,如果不用数据库,您可以直接做一个普通页面,只要文件名不变就可以了。
< %@LANGUAGE="VBSCRIPT"
CODEPAGE="936"% >
< !--#include file="cn.asp"-- >
< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>
< html xmlns="http://www.w3.org/1999/xhtml"
>
< head >
< meta http-equiv="Content-Type" content="text/html;
charset=utf-8" / >
< title >获取页面< /title >
< /head >
< body >
< %
dim rs
dim sql
Set rs = Server.CreateObject("ADODB.Recordset")
sql = "select * from test"
rs.open sql,cn,1,1
if not (rs.bof and rs.eof) then
Response.Write("< table >")
Response.Write(escape("< tr >< td >ID< /td ><
td >关键字< /td >< /tr >"))
do while not rs.eof
%>
< tr >< td >< %Response.Write(escape(rs("id")))%
>< /td >< td ><
%Response.Write(escape(rs("name")))% >< /td >< /tr
>
< %
rs.movenext
loop
Response.Write("< /table >")
end if
rs.close
set rs = nothing
% >
< /body >
< /html >