jQuery定时局部更新table数据,同步数据库数据!

本文介绍了一个使用HTML、JavaScript和Java实现的自动刷新页面功能,通过AJAX技术定时从服务器获取专家类别列表,并更新显示在网页表格中。支持用户自定义刷新间隔。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

html代码:

<%@ page contentType="text/html;charset=UTF-8" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" charset="UTF-8"
<span style="white-space:pre">	</span>src="${ctx}/resources/js/jquery-1.7.1.min.js"></script>

</head>
<body  class="easyui-layout" style="height: 100%" onload="searchData();">
<div>
<tr>
<td>设置自动刷新时间:<s:select id="s1" name="timer" list="#{'0':'30秒','1':'1分钟','2':'5分钟'}" theme="simple" ></s:select></td>
<td><input type="button" value="待定"/></td>
<td><input type="button" value="待定"/></td>
<td><input type="button" value="待定"/></td>
</tr>
</div>
<div id="div" >
<table id="resultTable"  width="100%" border="1" align="center" cellPadding="0" cellSpacing="0" >  
   <thead> 
     <span style="white-space:pre">	</span><tr>  
            <td nowrap >专家编号</td>  
            <td nowrap >专家分类</td>  
            <td nowrap >描述</td>  
       </tr>
    </thead>
     <tbody>  
        
    </tbody>
</table> 
</div>
</body>
</html>

JavaScript代码:

<script type="text/javascript">
var value=undefined;
var id=undefined;
//ajax查询记录信息   
function searchData(){ 
<span style="white-space:pre">	</span> /* alert('进来了!'); */  
        $.ajax({   
            url:'/iims/expertCategory/expert-category!myList.action',   
            cache:false,
            dataType:'json',
            success:function(buffer){
            	//清除Table 
	 			$("#resultTable").find('tbody').html(""); 
            	$.each(buffer, function(idx,item){   
            	 if(idx<buffer.length){
            	 $("#resultTable").find('tbody').append("<tr ><td nowrap>"+item.serialNumber+"</td><td nowrap>"+item.category+"</td><td nowrap>"+item.description+"</td></tr>");   
            		 return true;
            	 }else{
            		 return false;
            	 }
            	 });   
            }
       });
        $("select").change(function(){
          	 id = $(this).val();
          	if(id==0){value=30000;}
          	else if(id==1){value=60000;}
          	else if(id==2){value=300000;}
         	 });
        if(value==undefined){
        	//默认30秒刷新一次
        	setTimeout("searchData()",30000); 
        }else{
        	setTimeout("searchData()",value);
        }
}
</script>
java代码:

Action的myList方法

@WebRequest(RequestType.AJAX)
	public void myList(){
<span style="white-space:pre">		</span>//返回ExperCategory对象的一个list集合
		List<ExpertCategory> list=expertCategoryService.findAllExpertCategory();
		WebUtils.renderJson(list);
	}

WebUtils工具类的代码

<pre name="code" class="java">import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
public final class WebUtils {
	// -- header 常量定义 --//
	private static final String HEADER_ENCODING = "encoding";
	private static final String HEADER_NOCACHE = "no-cache";
	private static final String DEFAULT_ENCODING = "UTF-8";
	private static final boolean DEFAULT_NOCACHE = true;

	// -- Content Type 定义 --//
	public static final String TEXT_TYPE = "text/plain";
	public static final String JSON_TYPE = "application/json";
	public static final String XML_TYPE = "text/xml";
	public static final String HTML_TYPE = "text/html";
	public static final String JS_TYPE = "text/javascript";
	public static final String EXCEL_TYPE = "application/vnd.ms-excel";

	private static ObjectMapper mapper = new ObjectMapper();
	
	private static Logger logger = LoggerUtils.getLogger(WebUtils.class);
	
	private WebUtils() {
		
	}
	/**
	 * 直接输出JSON,使用Jackson转换Java对象.
	 * 
	 * @param data
	 *            可以是List<POJO>, POJO[], POJO, 也可以Map名值对.
	 * @see #render(String, String, String...)
	 */
	public static void renderJson(final Object data, final String... headers) {
		HttpServletResponse response = initResponseHeader(JSON_TYPE, headers);
		try {
			mapper.writeValue(response.getWriter(), data);
		} catch (Exception e) {
			logger.warn(e.getMessage(), e);
		}
	}
	/**
	 * 分析并设置contentType与headers.
	 */
	private static HttpServletResponse initResponseHeader(final String contentType, final String... headers) {
		// 分析headers参数
		String encoding = DEFAULT_ENCODING;
		boolean noCache = DEFAULT_NOCACHE;
		for (String header : headers) {
			String headerName = StringUtils.substringBefore(header, ":");
			String headerValue = StringUtils.substringAfter(header, ":");

			if (StringUtils.equalsIgnoreCase(headerName, HEADER_ENCODING)) {
				encoding = headerValue;
			} else if (StringUtils.equalsIgnoreCase(headerName, HEADER_NOCACHE)) {
				noCache = Boolean.parseBoolean(headerValue);
			} else {
				throw new IllegalArgumentException(headerName + "不是一个合法的header类型");
			}
		}

		HttpServletResponse response = ServletActionContext.getResponse();

		// 设置headers参数
		String fullContentType = contentType + ";charset=" + encoding;
		response.setContentType(fullContentType);
		if (noCache) {
			setDisableCacheHeader(response);
		}

		return response;
	}

}



运行效果如下,根据设置的时间会同步数据库的数据
<img src="https://img-blog.youkuaiyun.com/20150326150809693?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvamFtZXNzc2VtYWo=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值