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

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 οnlοad="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;
   }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值