日期:2014-05-16 浏览次数:20617 次
Ajax 介绍三
<%@ page language="java" import= "java.util.*" pageEncoding="UTF-8" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head > <title >Product </title> <script type="text/javascript"> function getXMLHttpRequest() { if(window.XMLHttpRequest) { return new XMLHttpRequest(); } else { return new ActiveXObject("Microsoft.XMLHTTP" ); } } //加载热销排行榜信息 function loadHotsale() { var xhr = getXMLHttpRequest(); alert(xhr); var url = "hotsale.do?size=2" ; xhr.open( "GET",url); xhr.onreadystatechange = function() { var li = document.getElementById("s1" ); var str = "" ; if(xhr.readyState == 4&&xhr.status==200) { var txt = xhr.responseText; var arr = eval("(" +txt+")" ); //循环JSON数组 for(var i=0;i<arr.length;i++) { str += "<li>"+arr[i].name+" "+arr[i].qty+"</li>"; alert(str); } li.innerHTML = str; } }; xhr.send( null); } setInterval("loadHotsale()", 1000); </script > </head > <body > <div > <ul> <li> 钓鱼岛最新进展 </li> <li> 钓鱼岛历史</li > <li> 钓鱼岛能否开战 </li> </ul> </div > <div > <h3 >热销排行榜 </h3> <ol id="s1"> <li> BMW 3000</ li> <li> Q7 3000</ li> <li> Q5 2300</ li> </ol > </div > </body > </html>
public class Sale { private int id ; private String name; private int qty ; public int getId() { return id ; } public void setId(int id) { this.id = id; } public String getName() { return name ; } public void setName(String name) { this.name = name; } public int getQty() { return qty ; } public void setQty(int qty) { this.qty = qty; } }
public class SaleDAO { public List<Sale> findHotSale( int size) throws Exception { String sql = "select * from t_sale order by qty desc limit 0,?"; Connection con = null; try{ con = DBUtil. getConnection(); PreparedStatement stmt = con.prepareStatement(sql); stmt.setInt(1, size); stmt.executeQuery(); ResultSet rs = stmt.getResultSet(); List<Sale> list = new ArrayList<Sale>(); while(rs.next()) { Sale s = new Sale(); s.setId(rs.getInt( "id")); s.setName(rs.getString( "name")); s.setQty(rs.getInt( "qty")); list.add(s); } return list; } catch (Exception e) { return null ; } finally{ DBUtil. close(con); } } }