使用jquery ajax 动态加载数据

      首先由一个bean 这是要加载的数据类型

public class Stock {
	private String code;
	private String name;
	private double price;
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
}

 这是servlet 当然也可以用struts2和SpringMVC的action,但是要设置返回的数据时json字符串

public class ActionServlet extends HttpServlet {

	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
			if(1 == 2){
				throw new ServletException("模拟一个系统异常");
			}
			/*
			 * 模拟生成几支股票的信息
			 */
			List<Stock> stocks = 
				new ArrayList<Stock>();
			Random r = new Random();
			DecimalFormat df = 
				new DecimalFormat("#.##");
			for(int i=0;i<8;i++){
				Stock s = new Stock();
				s.setCode("60001" + r.nextInt(10));
				s.setName("深发展" + r.nextInt(10));
				double price = r.nextDouble() * 100;
				s.setPrice(Double.parseDouble(
						df.format(price)));
				stocks.add(s);
			}
			JSONArray jsonArr = 
				JSONArray.fromObject(stocks);
			String jsonStr = jsonArr.toString();
			System.out.println(jsonStr);
			out.println(jsonStr);
		}
		out.close();
	}

}

 这是jsp

<%@page pageEncoding="utf-8" contentType="text/html;charset=utf-8" %>
<html>
	<head>
		<style>
			#d1{
				width:500px;
				height:300px;
				border:1px solid red;
				background-color:black;
				margin-left:350px;
				margin-top:40px;
			}
			#d2{
				background-color:red;
				color:white;
				height:40px;
			}
			table{
				color:white;
				font-size:24px;
			}
		</style>
		<script type="text/javascript" src="js/jquery-1.4.3.js">
		</script>
		<script type="text/javascript">
			$(function(){
				setInterval(f1,5000);
			});
			function f1(){
				$.ajax({
					'url':'quoto.do',
					'type':'post',
					'dataType':'json',
					'success':function(data){
						//data是服务器返回的数据
						$('#tb1').empty();
						for(i=0;i<data.length;i++){
							var s = data[i];
							$('#tb1').append(
							'<tr><td>' + s.code 
							+ '</td><td>' + s.name 
							+ '</td><td>' + s.price 
							+ '</td></tr>');
						}
					},
					'error':function(){
						$('#tb1').empty();
						$('#tb1').append(
						"<tr><td colspan='3'>查询不到最新的股票行情</td></tr>");
					}
				});
			}
		</script>
	</head>
	<body style="font-size:30px;font-style:italic;">
		<div id="d1">
			<div id="d2">股票实时行情</div>
			<div>
				<table width="100%" cellpadding="0" 
				cellspacing="0">
					<thead>
						<tr>
							<td>代码</td>
							<td>名称</td>
							<td>价格</td>
						</tr>
					</thead>
					<tbody id="tb1">
					</tbody>
				</table>
			</div>
		</div>
	</body>
</html>
 

相关推荐