您的位置:首页 > 编程语言 > Java开发

struts ajax应用二 自动更新获取服务器数据

2009-05-15 14:44 495 查看
autoupdate.jsp:

< html xmlns = "http://www.w3.org/1999/xhtml" > <head > <meta http - equiv = "Content-Type"
content = "text/html; charset=UTF-8" / ><title > Auto Update < /title>
</head > <script type = "text/javascript" >
var xmlHttp;
//创建XMLHttp对象实例
function createXMLHttpRequest() {
if (window.ActiveXObject) { //如果是IE
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}

function doStart() {
createXMLHttpRequest();
var url = "autoupdate.do";
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = startcallback;
xmlHttp.send(null);
}

function startcallback() {
if (xmlHttp.readyState == 4) { //判断请求的状态(0=未初始化,1=正在加载,2=已经加载,3=交互,4=完成)
if (xmlHttp.status == 200) { //判断Server的Http状态码(200对应 ok , 404对应Not Found,204对应返回空)
setInterval("doStart()", 3000); //设置循环调用
refreshTime(xmlHttp.responseText);
}
}
}

function refreshTime(Textstr) {
var timeobj = document.getElementById("showtime");
timeobj.value = Textstr;

}

< /script>
<body onload="doStart()">
<input type="text" id="showtime" / >

<input type = "button" id = "testbtn" value = "Click me"onclick = "javascript:refreshTime('cxm come')" / >

</body>
</html >

Server Action:

package cxm.ajax;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.*;
import java.io.PrintWriter;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

public class autoupdate extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {

PrintWriter pout = response.getWriter();

pout.print(getStringDate());
System.out.println("运行了");
pout.flush();
pout.close();
return null;
}

public static String getStringDate() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(currentTime);
return dateString;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐