一个简单的利用Ajax进行动态查询的例子。

此例就是利用Ajax实现异步传输。通过异步传输对象发送请求和接受响应。请求的为服务器端组件,在这里使用Servlet实现。响应的结果为XML格式,通过在网页中利用JS使用DOM进行内容解析,实现内容的动态生成。

下面讲解例子:

首先准备表,在这里使用Oracle数据库,数据库名称为GoldDB,在其中的frank模式下建立表MyTable,表中包含三个字段分别为:pid,pname,age。以后的检索条件利用age,检索age大于某一条件的结果。

首先创建Web Project,在其中创建index.jsp,作为与用户交互的页面,动态的处理也在此页面利用Ajax完成。

主体页面的设计如下:

<body>
    age:<input type="text" id="searchAge"/><input type="button" οnclick="searchPerson()" value="Search"/><br>
    <table id="mytable" border="16" width="80%">
     <tr bgcolor="#00ffff">
      <td>pid</td>
      <td>pname</td>
      <td>age</td>
     </tr>
     <tbody id="mybody">
     </tbody>
    </table>
  </body>

非常的简单,此页面存在一个文本框,id为searchAge,用来输入查询条件数值,另外存在一个按钮用作提交,调用JS方法searchPerson

页面中存在一个查询结果的现实Table,注意,必须建立tbody标记,因为动态生成的结果要在tbody中操作。id为mytable

当点击按钮的时候调用searchPerson方法,方法如下:


function searchPerson(){ createXMLHttpRequest(); var age=document.getElementById("searchAge").value; var queryString="testServlet?age="+age; xmlHttp.onreadystatechange=callback; xmlHttp.open("GET",queryString,true); xmlHttp.send(null); }

 

此方法首先利用createXMLHttpRequest方法创建异步传输对象,然后取得条件文本框中输入的年龄数值,然后生成请求URL

var queryString="testServlet?age="+age;
利用刚才的数值作为参数

然后利用回调

xmlHttp.onreadystatechange=callback;
当异步传输对象的状态发生任何改变的时候调用callback方法

最后代开查询:xmlHttp.open("GET",queryString,true);

最有发送:xmlHttp.send(null);,因为采用的是GET请求,所以不需要任何的参数信息,所以此处是null

因为需要创建异步传输对象,所以此方法如下:


var xmlHttp; function createXMLHttpRequest(){ if(window.ActiveXObject){ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); }else if(window.XMLHttpRequest){ xmlHttp=new XMLHttpRequest(); } }

 

就是根据浏览器的不同,采用不同的方式创建异步传输对象

回调的函数callback


function callback(){ if(xmlHttp.readyState==4){ if(xmlHttp.status==200){ makeTable(); } } }

 

当请求完成,且成功,则调用makeTable方法

makeTable方法非常的简单就是首先清理上次的查询结果,然后利用响应回来的XML数据进行DOM解析形成新的表格数据


function makeTable(){ clearTable(); var mybody=document.getElementById("mybody"); var results=xmlHttp.responseXML.getElementsByTagName("person"); for(i=0;i<results.length;i++){ var row=document.createElement("tr"); var cellPid=document.createElement("td"); var cellPname=document.createElement("td"); var cellAge=document.createElement("td"); cellPid.appendChild(document.createTextNode(results[i].getElementsByTagName("pid")[0].firstChild.nodeValue)); cellPname.appendChild(document.createTextNode(results[i].getElementsByTagName("pname")[0].firstChild.nodeValue)); cellAge.appendChild(document.createTextNode(results[i].getElementsByTagName("age")[0].firstChild.nodeValue)); row.appendChild(cellPid); row.appendChild(cellPname); row.appendChild(cellAge); mybody.appendChild(row); } } function clearTable(){ var mybody=document.getElementById("mybody"); while(mybody.childNodes.length>0){ mybody.removeChild(mybody.childNodes[0]); } }


 整体页面代码如下:

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'index.jsp' starting page</title>
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
 <script type="text/javascript">
  var xmlHttp;
  function createXMLHttpRequest(){
       if(window.ActiveXObject){
          xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
       }else if(window.XMLHttpRequest){
          xmlHttp=new XMLHttpRequest();
       }
  }
  function searchPerson(){
   createXMLHttpRequest();
   var age=document.getElementById("searchAge").value;
   var queryString="testServlet?age="+age;
   xmlHttp.onreadystatechange=callback;
   xmlHttp.open("GET",queryString,true);
   xmlHttp.send(null);
  }
  function callback(){
  
   if(xmlHttp.readyState==4){
    if(xmlHttp.status==200){
     
     makeTable();
    }
   }
  }
  function makeTable(){
   clearTable();
   var mybody=document.getElementById("mybody");
   var results=xmlHttp.responseXML.getElementsByTagName("person");
   for(i=0;i<results.length;i++){
    var row=document.createElement("tr");
    var cellPid=document.createElement("td");
    var cellPname=document.createElement("td");
    var cellAge=document.createElement("td");
    cellPid.appendChild(document.createTextNode(results[i].getElementsByTagName("pid")[0].firstChild.nodeValue));
    cellPname.appendChild(document.createTextNode(results[i].getElementsByTagName("pname")[0].firstChild.nodeValue));
    cellAge.appendChild(document.createTextNode(results[i].getElementsByTagName("age")[0].firstChild.nodeValue));
    row.appendChild(cellPid);
    row.appendChild(cellPname);
    row.appendChild(cellAge);
    mybody.appendChild(row);
   }
  
  }
  function clearTable(){
   var mybody=document.getElementById("mybody");
   while(mybody.childNodes.length>0){
    mybody.removeChild(mybody.childNodes[0]);
   }
  }
 </script>
  </head>
 
  <body>
    age:<input type="text" id="searchAge"/><input type="button" οnclick="searchPerson()" value="Search"/><br>
    <table id="mytable" border="16" width="80%">
     <tr bgcolor="#00ffff">
      <td>pid</td>
      <td>pname</td>
      <td>age</td>
     </tr>
     <tbody id="mybody">
     </tbody>
    </table>
  </body>
</html>

 请求的组件为servlet,代码如下(只列出doGet方法,其他的方法为默认的):

public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  response.setContentType("text/xml");
  
  response.setHeader("pragma", "no-cache");
  response.setHeader("cache-control", "No-cache");
  response.setDateHeader("expires", 0);
  Connection conn=null;
  PreparedStatement pstmt=null;
  ResultSet rst=null;
  String strAge=request.getParameter("age");
  try{
   Class.forName("oracle.jdbc.driver.OracleDriver");
   conn=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:GoldDB","root","123456");
   String strSQL="select * from MyTable where age>?";
   pstmt=conn.prepareStatement(strSQL);
   pstmt.setInt(1, Integer.parseInt(strAge));
   rst=pstmt.executeQuery();
   StringBuffer strb=new StringBuffer();
   strb.append("<persons>");
   while(rst.next()){
    strb.append("<person>");
    strb.append("<pid>"+rst.getInt(1)+"</pid>");
    strb.append("<pname>"+rst.getString(2)+"</pname>");
    strb.append("<age>"+rst.getInt(3)+"</age>");
    strb.append("</person>");
   }
   strb.append("</persons>");
   System.out.println(strb.toString());

   response.getWriter().write(strb.toString());
  }catch(ClassNotFoundException ex){
   ex.printStackTrace();
  }catch(SQLException ex){
   ex.printStackTrace();
  }
  
 }

 此方法就是利用JDBC检索对应的数据库表,然后检索数据,形成XML格式内容。注意利用StringBuffer生成。最后响应给客户端。