ajxatest.php:
< !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" >
< html >
< head >
< meta http-equiv ="Content-Type" content ="text/html; charset=UTF-8" >
< title >Insert title here </title>
< script type ="text/javascript" src ="ajxatest.js" >

</script>
< style type ="text/css" >
.displaybox{
  width:150px;
     background-color:#ffffff;
     border:2px solid #000000;
     padding:10px;
     font:24px normal verdana,helvetica,arial,sans-serif;
    
}

</style>
</head>
< body     bgcolor ="#cccccc" onload ="getServerTime()" >
< h1 >ajax demon </h1>
< h2 >get the server time without page refresh </h2>
< form >
< input type ="button" value ="get server time" onclick ="getServerTime()" > </input>
</form>
< div class ="displaybox" id ="showtime" > </div>

</body>
</html>
 
ajxatest.js:
function getXMLHTTPRequest(){
   var req = null;
   try{
    req = new XMLHttpRequest(); //e.g firefox
  }
   catch(err1){
     try{
      req = new ActiveXObject( "Msxml2.XMlHTTP"); // some versions IE
    }
     catch(err2){
       try{
        req = new ActiveXObject( "Microsoft.XMlHTTP"); // some versions IE
      }
       catch(err3){
        req = false;
      }        
    }
  }
   return req;
}

var http = getXMLHTTPRequest();

function getServerTime(){
   var myurl = 'http: //127.0.0.1/js/getdate.php';
  myRand = parseInt(Math.random()*99999999999999999);
   var modurl = myurl + "?rand=" + myRand;
   //document.write(modurl);
  http.open( "GET",modurl, true);
  http.onreadystatechange = useHTTPResponse;
  http.send( null);
}

function useHTTPResponse(){
   if(http.readyState == 4){
     if(http.status == 200){
       var timeValue = http.responseXML.getElementsByTagName( "timenow")[0];
      document.getElementById('showtime').innerHTML = timeValue.childNodes[0].nodeValue;
    } else{
      document.getElementById('showtime').innerHTML = '<img src= "anim.gif">';
    }
  }
}
getdate.php:
<?php
header('Content-Type: text/xml');
echo "<?xml version=\"1.0\"?><timenow>" . date('H:i:s')."</timenow>";
?>
 
里面用到一个图片,附件中有
 
这个例子非常简单,但很实用,对于初学者学习ajax有相当的意义。可以通过个例子了解ajax的工作原理。