首页 > 编程 > JSP > 正文

网页无闪自动局部刷新实例

2024-09-05 00:17:30
字体:大 中 小
来源:转载
供稿:网友

我们在网页制作的过程中经常会遇到及时刷新数据的问题,如果使用<meta http-equiv=refresh content="300">的方法,会造成整个屏幕不断闪烁刷新的效果,这会降低用户的操作满意度。所以我们需要一种可以实现无闪自动刷新数据的方法来解决以上问题。

实例解决问题:

希望实现用户在进入系统以后(整个session的时效之内),如果收到新邮件则发出声音提示。

实现思路:

1.首页部分:<body onload="init('<%=ses_userBean.getUsername()%>');"> // load时调用init(user);

2.js部分:用XMLHTTP实现页面局部刷新,调用check_mail.jsp对后台数据库进行检索判断并返回结果。

 

  1. <!-- 
  2. var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
  3. var checkresult=null; 
  4. var username =null;  
  5.  
  6. function init(user){ 
  7. username=user; 
  8. window.setInterval('Checkmail()',5000);//每隔5秒自动调用Checkmail() 
  9. } 
  10.  
  11. function Checkmail() 
  12. { 
  13. xmlhttp.open("POST", "check_mail.jsp?uName="+username, false); 
  14. xmlhttp.onreadystatechange = updatePage; 
  15. xmlhttp.send(); 
  16. } 
  17. function updatePage() { 
  18. if (xmlhttp.readyState < 4) { 
  19. test1.innerHTML="loading..."; 
  20. } 
  21. if (xmlhttp.readyState == 4) { 
  22. var response = xmlhttp.responseText; 
  23. if(response==1){//判断为假 
  24. test1.innerHTML="&nbsp;"; 
  25. checkresult=1; 
  26. } 
  27. else{//判断为真 
  28. test1.innerHTML="<img alt='新邮件' src='img/tp024.gif'><EMBED src='music/nudge.wma' hidden=true autostart=true loop=false>"; 
  29. checkresult=0; 
  30. } 
  31. } 
  32. } 
  33. // --> 

3.check_mail.jsp

  1. <%@ page contentType="text/html; charset=GBK" %> 
  2. <%@ page errorPage="error/login_error.jsp"%> 
  3. <%@ page import="myweb.*" %> 
  4. <%@ page import="java.sql.*" %> 
  5. <% 
  6. String user=request.getParameter("uName"); 
  7. Connection conn=null; 
  8. try{ 
  9. conn=DBConnection.getConnection(); 
  10. PreparedStatement pStat=conn.prepareStatement("select * from message where r_name='"+user+"' and status=0"); 
  11. ResultSet rs=pStat.executeQuery(); 
  12. if(rs.next()){//有记录 
  13. response.getWriter().print(0); 
  14. }else{ 
  15. response.getWriter().print(1); 
  16. } 
  17. }finally{ 
  18. if(conn!=null) conn.close(); 
  19. } 
  20. %> 


4.首页结果显示

将<span id="test1"></span>插入指定位置。
 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表