利用ajax和JSP技術實現網頁中表單的局部重新整理(只重新整理表單資料,而不重新整理整個頁面)__JSP

來源:互聯網
上載者:User

在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:這裡為簡單舉例,樣式什麼的可以自行添加和修改。有錯誤歡迎指正。)

  

       


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.