我們在網頁制作的過程中經常會遇到及時刷新數據的問題,如果使用<meta http-equiv=refresh content="300">的方法,會造成整個屏幕不斷閃爍刷新的效果,這會降低用戶的操作滿意度。所以我們需要一種可以實現無閃自動刷新數據的方法來解決以上問題。
實例解決問題:
希望實現用戶在進入系統以后(整個session的時效之內),如果收到新郵件則發出聲音提示。
實現思路:
1.首頁部分:<body onload="init('<%=ses_userBean.getUsername()%>');"> // load時調用init(user);
2.js部分:用XMLHTTP實現頁面局部刷新,調用check_mail.jsp對后臺數據庫進行檢索判斷并返回結果。
- <!--
- var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
- var checkresult=null;
- var username =null;
- function init(user){
- username=user;
- window.setInterval('Checkmail()',5000);//每隔5秒自動調用Checkmail()
- }
- function Checkmail()
- {
- xmlhttp.open("POST", "check_mail.jsp?uName="+username, false);
- xmlhttp.onreadystatechange = updatePage;
- xmlhttp.send();
- }
- function updatePage() {
- if (xmlhttp.readyState < 4) {
- test1.innerHTML="loading...";
- }
- if (xmlhttp.readyState == 4) {
- var response = xmlhttp.responseText;
- if(response==1){//判斷為假
- test1.innerHTML=" ";
- checkresult=1;
- }
- else{//判斷為真
- test1.innerHTML="<img alt='新郵件' src='img/tp024.gif'><EMBED src='music/nudge.wma' hidden=true autostart=true loop=false>";
- checkresult=0;
- }
- }
- }
- // -->
3.check_mail.jsp
- <%@ page contentType="text/html; charset=GBK" %>
- <%@ page errorPage="error/login_error.jsp"%>
- <%@ page import="myweb.*" %>
- <%@ page import="java.sql.*" %>
- <%
- String user=request.getParameter("uName");
- Connection conn=null;
- try{
- conn=DBConnection.getConnection();
- PreparedStatement pStat=conn.prepareStatement("select * from message where r_name='"+user+"' and status=0");
- ResultSet rs=pStat.executeQuery();
- if(rs.next()){//有記錄
- response.getWriter().print(0);
- }else{
- response.getWriter().print(1);
- }
- }finally{
- if(conn!=null) conn.close();
- }
- %>
4.首頁結果顯示
將<span id="test1"></span>插入指定位置。
新聞熱點
疑難解答