在web開發中有時有局部重新整理的需求,這樣做的好處是克服了頁面整體重新整理對網路速度受限的情況。
1.MySQL資料表如下(簡單舉例):
表名:stu_info
stuId int PK NN
stuName varchar(45) NN
stuDesc varchar(45)
2.建立wk.jsp,代碼如下:
<span style="color:#330033;"><%@ page contentType="text/html; charset=utf-8" %><head> <META http-equiv=Content-Type content="text/html; charset=utf-8"> </head> <script language="javascript"> var XMLHttpReq; //建立XMLHttpRequest對象 function createXMLHttpRequest() { if(window.XMLHttpRequest) { //Mozilla 瀏覽器 XMLHttpReq = new XMLHttpRequest(); } else if (window.ActiveXObject) { // IE瀏覽器 try { XMLHttpReq = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { XMLHttpReq = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} } } } //發送請求函數 function sendRequest() { createXMLHttpRequest(); var url = "ajax.jsp"; XMLHttpReq.open("GET", url, true); XMLHttpReq.onreadystatechange = processResponse;//指定響應函數 XMLHttpReq.send(null); // 發送請求 } // 處理返回資訊函數 function processResponse() { if (XMLHttpReq.readyState == 4) { // 判斷對象狀態 if (XMLHttpReq.status == 200) { // 資訊已經成功返回,開始處理資訊 DisplayHot(); setTimeout("sendRequest()", 1000); } else { //頁面不正常 window.alert("您所請求的頁面有異常。"); } } } function DisplayHot() { var yan1 = XMLHttpReq.responseXML.getElementsByTagName("id"); var yan = XMLHttpReq.responseXML.getElementsByTagName("name"); var yan2 = XMLHttpReq.responseXML.getElementsByTagName("description"); var ta = ""; for(var i=0;i<yan.length;i++){ var id = yan1[i].firstChild.nodeValue; var name = yan[i].firstChild.nodeValue; var desc = yan2[i].firstChild.nodeValue; ta+="<tr align=left><td><table><td width=100>"+id+"</td><td width=200>"+name+"</td><td width=200>"+desc+"</td></table></td></tr>"; // document.getElementById(res).innerHTML = name; // res = res +i.toString(); } document.getElementById("res").innerHTML = ta;} </script> <body onload =sendRequest() > <table style="BORDER-COLLAPSE: collapse" borderColor=#111111 cellSpacing=0 cellPadding=0 width=400 bgColor=#f5efe7 border=0> <TR> <TD align=middle bgColor=#dbc2b0 height=19 colspan="3"><B>學生資訊</B> </TD> </TR> <tr><td>學號</td><td>姓名</td><td>備忘</td></tr> </table> <table border=1 width=400> <div id="res"></div> </table> </body> </table></span>
3.建立Conn.jsp,代碼如下:
<span style="color:#330033;"></pre><p><pre name="code" class="html"><%@ page contentType="text/html; charset=utf-8" import="java.sql.*, javax.naming.Context, javax.naming.InitialContext" errorPage=""%> <%!Connection conn = null; Statement stmt = null; ResultSet rs = null; public void jspInit() { try { Class.forName("com.mysql.jdbc.Driver"); //建立串連 conn = DriverManager.getConnection( "jdbc:mysql://192.168.1.106:3306/acsystem", "ouyang", "ouyang"); //if(conn!=null){ //System.out.println("connect success"); //}//Context initCtx = new InitialContext(); //Context ctx = (Context) initCtx.lookup("java:comp/env"); //擷取串連池對象 //Object obj = (Object) ctx.lookup("jdbc/javasky"); //類型轉換 //javax.sql.DataSource ds = (javax.sql.DataSource) obj; //conn = ds.getConnection(); stmt = conn.createStatement(); } catch (Exception ex) { System.out.println(ex.toString()); } } public void Exec(String sql) { jspInit(); try { stmt.executeUpdate(sql); } catch (Exception e) { System.out.print(e.toString()); } } public ResultSet getRs(String sql) throws SQLException { jspInit(); try { rs = stmt.executeQuery(sql); return rs; } catch (Exception e) { System.out.print(e); return null; } } public ResultSet executeQuery(String sql) throws Exception { jspInit(); try { sql = new String(sql.getBytes("GBK"), "utf-8"); stmt = conn.createStatement( java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE, java.sql.ResultSet.CONCUR_READ_ONLY); rs = stmt.executeQuery(sql); } catch (SQLException ex) { System.out.println("sql.executeQuery:" + ex.getMessage()); } return rs; } public String getS(String Str) { try { byte b[] = Str.getBytes("ISO-8859-1"); Str = new String(b, "UTF-8"); } catch (Exception ee) { ee.printStackTrace(); } return Str; }%> </span>
4.建立ajax.jsp,代碼如下:
<span style="color:#330033;"><%@ page contentType="text/html; charset=utf-8" import="java.sql.*,java.util.*" errorPage="" %> <%@ include file="Conn.jsp" %> <% try{ ResultSet rs=getRs("select * from stu_info order by stuId asc"); StringBuffer content=new StringBuffer(""); response.setContentType("text/xml;charset=UTF-8"); response.setHeader("Cache-Control","no-cache"); //out.println("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"); out.println("<response>"); while(rs.next()){ String id=rs.getString("stuId"); int stuId = Integer.parseInt(id); String stuName=rs.getString("stuName"); String stuDesc=rs.getString("stuDesc"); System.out.println(stuId); //out.println("<content>"); out.println("<id>" +stuId+ "</id>"); out.println("<name>" +stuName+ "</name>"); out.println("<description>" +stuDesc+ "</description>"); //out.println("</content>"); } out.println("</response>"); out.close(); } catch(Exception e){ e.printStackTrace(); } %> </span>
5.把上述3個頁面放在項目同一個檔案夾下,運行wk.jsp 即可得到表單stu_info的資料。
(PS:這裡為簡單舉例,樣式什麼的可以自行添加和修改。有錯誤歡迎指正。)