jsp中Ajax實現不刷屏的前提下實現頁面定時刷新的功能

最近在網絡上找了一些相關文章, Ajax實現不刷屏的前提下實現頁面定時刷新的功能,結果發現網絡上都是千篇一律的代碼,而且都有錯誤的,沒有辦法了,只好自己寫了,剛剛寫好,共享一下下,代碼如下 

index.jsp 
<%@ page language="java" import="java.util.*" pageEncoding="Gb2312"%> 
<% 
String path = request.getContextPath(); 
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 
%> 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
  <head> 
    <base href="<%=basePath%>"> 
     
    <title>My JSP 'index.jsp' starting page</title> 
     
 <meta http-equiv="pragma" c> 
 <meta http-equiv="cache-control" c> 
 <meta http-equiv="expires" c>     
 <meta http-equiv="keywords" c> 
 <meta http-equiv="description" c> 
 <!-- 
 <link rel="stylesheet" type="text/css" href="styles.css"> 
 --> 
<script type="text/javascript"> 
<!-- 
//建立XMLHttpRequest對象 
var xmlhttp; 
try{ 
    xmlhttp= new ActiveXObject('Msxml2.XMLHTTP'); 
}catch(e){ 
    try{ 
        xmlhttp= new ActiveXObject('Microsoft.XMLHTTP'); 
    }catch(e){ 
        try{ 
            xmlhttp= new XMLHttpRequest(); 
        }catch(e){} 
    } 

function getPart(url){ 
    xmlhttp.open("get",url,true); 
    xmlhttp.onreadystatechange = function(){ 
        if(xmlhttp.readyState == 4) 
        { 
            if(xmlhttp.status == 200) 
            { 
                if(xmlhttp.responseText!=""){ 
                    document.getElementById("partdiv").innerHTML = unescape(xmlhttp.responseText);         
                } 
            } 
            else{ 
                document.getElementById("partdiv").innerHTML = "數據加載出錯"; 
            } 
        } 
    } 
    xmlhttp.setRequestHeader("If-Modified-Since","0"); 
    xmlhttp.send(null); 

setInterval("getPart('test.jsp')",1000) 
//--> 
</script> 
</head> 
<body> 
index   
下面是test.jsp的數據 
<div id="partdiv"></div><!--局部刷新數據的容器--> 
</body> 
</html> 

test.jsp 
<%@ page language="java" import="java.util.*" pageEncoding="GB2312"%> 
<% 
String path = request.getContextPath(); 
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 
%> 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
  <head> 
    <base href="<%=basePath%>"> 
     
    <title>My JSP 'test.jsp' starting page</title> 
     
 <meta http-equiv="pragma" c> 
 <meta http-equiv="cache-control" c> 
 <meta http-equiv="expires" c>     
 <meta http-equiv="keywords" c> 
 <meta http-equiv="description" c> 
 <!-- 
 <link rel="stylesheet" type="text/css" href="styles.css"> 
 --> 
  </head> 
   
  <body> 
    這裏就是test頁面的內容了,在這個頁面上你想做什麼就做什麼<br/> 
    這樣就簡單的實現了Ajax不刷屏的前提下實現頁面定時刷新的功能 
    <br/> 
     
     
    希望大家以後多多支持本論壇 
  </body> 
</html>  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章