参考了IBM上关于AJAX的使用方法,代码也是从那摘的,简单组织了一下,做出了在页面显示服务器时间的一个小DEMO,拿出来晒晒。
一共有两个页面:
1、index.jsp:用来显示时间的,所有的AJAX操作都在这里
2、indexAction.jsp:被index.jsp的AJAX操作访问的页面,用来输出系统时间
附件为本次小DEMO
index.jsp的核心代码是:
1、获取XMLHttpRequest实例
function getRequest(){ /* Create a new XMLHttpRequest object to talk to the Web server */ var xmlHttp = false; /*@cc_on @*/ /*@if (@_jscript_version >= 5) try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e2) { xmlHttp = false; } } @end @*/ if (!xmlHttp && typeof XMLHttpRequest != 'undefined') { xmlHttp = new XMLHttpRequest(); } return xmlHttp; }
2、使用XMLHttpRequest的实例调用indexAction.jsp
function gettime(){ var xmlHttp = getRequest(); var url = "indexAction.jsp?date="+(new Date());//加个时间戳,防止页面缓存 // Open a connection to the server xmlHttp.open("GET", url, true); // Setup a function for the server to run when it's done xmlHttp.onreadystatechange = function(){//JS的匿名方法 //alert(xmlHttp.readyState); if (xmlHttp.readyState == 4) { var response = xmlHttp.responseText; //alert(response); document.getElementById("hello").innerText = response; } }; // Send the request xmlHttp.send(null); }
3、页面一打开就启动函数
function thread(){ gettime(); setTimeout("thread()",500);//使用JS的定时器启动AJAX调用 } //注册到页面的onload事件中 window.οnlοad=function(){ thread(); }
4、页面中只需要加上一个名字为hello的HTML标签就可以显示时间了
<h1 id="hello"></h1>
indexAction.jsp中代码很简单
但是由于我们上面的需要的返回值为纯的时间字符串,所以在编写的时候要注意,这个页面输出的HTML内容不能包含空行在前面(其实包含了也没问题,这是只是提一下),这个页面全部的代码如下(注意是全部代码哦):
<%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%><%
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
out.print(format.format(new java.util.Date(System.currentTimeMillis())));
%>
小贴士:JSP的import语句即类似这么写的<%@page import="java.text.SimpleDateFormat"%>都可能会出现空行。