今天向企业I班同学讲了ajax的原理,并做了一个简单的例子,用于实现一个页面无刷新动态显示当前服务器的时间:

可以看看放在网上的具体例子,访问地址为http://www.koonsoft.net/samples/ajax/now.html,该示例其实包含3个文件:

文件now.asp的代码如下(注:这个只是用于普通页面与AJAX的比较,不属于Ajax技术应用内容!):

<%=now%>

 

这是一个传统的asp文件,用于显示服务器的当前时间,如果不是点击刷新图标或者按下F5键,那么页面的内容永远不会刷新。

文件now_ajax.asp的代码如下:

<%
    
' 我是用来从服务器生成XML数据的文件
%>
<%
    Response.Write(
"<?xml version='1.0' encoding='UTF-8' ?>")
    Response.Write(
"<Z>")
    Response.Write(
"<hosttime>")
    Response.Write(
now)
    Response.Write(
"</hosttime>")
    Response.Write(
"</Z>")
%>

 

这个文件是用来生成并返回一个xml格式的数据文件,其中有一个节点为hosttime,它的值带代表当前服务器的时间。

最后主要用来呈现的now.html文件内容如下

 

<!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>
  
<title>Ajax显示当前服务器时间</title>
  
<meta name="generator" content="editplus" />
  
<meta name="author" content="" />
  
<meta name="keywords" content="" />
  
<meta name="description" content="" />
    
<script type="text/javascript">
    
var xmlHttp;

    
// 判断浏览器类型,进而生成合适浏览器的xmlhttprequest对象
    function createXMLHttpRequest()    {
        
if (window.ActiveXObject) {
            
// 如果是IE浏览器
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }

        
else if (window.XMLHttpRequest) {
            
// 如果是非IE浏览器
            xmlHttp = new XMLHttpRequest();
        }
        
    }


    
/*
    // 获取服务器的时间
    function getHostTime() 
    {    
        createXMLHttpRequest();        
        
        //xmlHttp.open("GET", "http://localhost/ajax/now_ajax.asp?timespan=" + new Date().getTime(),true);
        xmlHttp.open("GET", "http://localhost/ajax/now_ajax.asp?time=" + new Date().getTime(),true);                
        xmlHttp.onreadystatechange = callback;
        xmlHttp.send(null);

    }
    
*/


    
// 当访问url的时候发生的回调
    function callback() {
        
if (xmlHttp.readyState == 4{
            
if (xmlHttp.status == 200{
                setTimeout(
"pollServer()"2000);
                refreshTime();
            }

            
else
            
{
                alert(
"您访问的URL不存在!请检查网络.");
            }

        }

    }


    
function pollServer() {
        createXMLHttpRequest();
        
var url = "http://localhost/ajax/now_ajax.asp?time=" + new Date().getTime();
        xmlHttp.open(
"GET", url, true);
        xmlHttp.onreadystatechange 
= callback;
        xmlHttp.send(
null);
    }


    
function refreshTime()
    
{
        document.getElementById(
"results").innerHTML = xmlHttp.responseText;
    }

     
</script>
 
</head> 
 
<body>
    
<span id="results">我是用来显示数据的html</span>
    
<input type="button" value='进行httpRequest' onclick="pollServer()"></input>
 
</body>
 
</html>

 

具体的例子请见示例页面。交给大家的练习就是课堂上所说的内容,如果不事先自己动手查阅资料,肯定无法完成我布置的练习,希望大家有问题跟贴留言。

参考资料包括以下内容:

posted on 2008-09-20 22:30  田老师  阅读(361)  评论(0编辑  收藏  举报