ajax in action 第9章 jsp版 動態雙組合功能

來源:互聯網
上載者:User

資源:  使用ajax頁面(發送和響應);一個處理伺服器頁面;還使用了一個可重用net.js.
1.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>1.html</title>
 <script type="text/javascript" src="net.js"></script>
    <script type="text/javascript">
      function FillTerritory(oElem,oTarget){  //此函數啟動了Ajax請求

        var strValue = oElem.options[
                     oElem.selectedIndex].value; //從挑選清單中擷取值
        var url = &apos;DoubleComboXML.jsp&apos;; //設定目標URL
        var strParams = &apos;q=&apos; + strValue +
          "&f=" + oTarget.form.name +
          "&e=" + oTarget.name;      //建立參數字串
        var loader1 = new
        net.ContentLoader(url,FillDropDown,null,
                    "POST",strParams);     //啟動內容載入器
      }
      function FillDropDown(){    //使用來自XML響應的資料更新頁面
        var xmlDoc = this.req.responseXML.documentElement;
        var xSel = xmlDoc.
           getElementsByTagName(&apos;selectElement&apos;)[0];
        var strFName = xSel.
           childNodes[0].firstChild.nodeValue;
        var strEName = xSel.
           childNodes[1].firstChild.nodeValue;

        var objDDL = document.forms[strFName].
           elements[strEName];
        objDDL.options.length = 0;

        var xRows = xmlDoc.
          getElementsByTagName(&apos;entry&apos;);
        for(i=0;i<xRows.length;i++){
          var theText = xRows[i].
              childNodes[0].firstChild.nodeValue;
          var theValue = xRows[i].
              childNodes[1].firstChild.nodeValue;
          var option = new Option(theText,
                            theValue);
          objDDL.options.add(option,
                          objDDL.options.length);
        }
      }
    </script>
  </head>
 
  <body>
       <form name="Form1">
      <select name="ddlRegion" onchange="FillTerritory(this,document.Form1.ddlTerritory)">
        <option value="-1">Pick A Region</option>
        <option value="1">Eastern</option>
        <option value="2">Western</option>
        <option value="3">Northern</option>
        <option value="4">Southern</option>
      </select>
      <select name="ddlTerritory"></select>
    </form>
  </body>
</html>

DoubleComboXML.xml(定義XML響應格式,用完後可以刪掉)
<?xml version="1.0" ?>
<selectChoice>
 <selectElement>
  <formName>Form1</formName>
  <formElem>ddlTerritory</formElem>
 </selectElement>
 <entry>
  <optionText>select A Territory</optionText>
  <optionValue>-1</optionValue>
 </entry>
 <entry>
  <optionText>TerritoryDescription</optionText>
  <optionValue>TerritoryID</optionValue>
 </entry>
</selectChoice>

DoubleComboXML.jsp
<%@ page language="java" import="java.util.*,java.sql.*,java.io.*" pageEncoding="GB2312"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP &apos;DoubleComboXML.jsp&apos; 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">
 -->

  </head>
 
  <body>
   <%
    String  strForm=request.getParameter("f");
    String strElem=request.getParameter("e");
    String strQuery  =request.getParameter("q");
  Class.forName("com.mysql.jdbc.Driver").newInstance();    
  String   url   ="jdbc:mysql://localhost/demo?user=root&password=";  
  Connection   conn=   DriverManager.getConnection(url);    
  Statement   stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);    
   String   sql="select  *  from   tb_area where father="+strQuery;   
  ResultSet   rs=stmt.executeQuery(sql);      
     
//下面使用定義的XML格式來輸出XML文檔
  StringBuilder strXML =new StringBuilder("<?xml version=&apos;1.0&apos; ?>");
      strXML.append("<selectChoice>");
       strXML.append("<selectElement>");
        strXML.append("<formName>"+strForm+"</formName>");
         strXML.append("<formElem>"+strElem+"</formElem>");
          strXML.append("</selectElement>");
           if(rs.next())
             {
               strXML.append("<entry>");
            strXML.append("<optionText>select A Territory</optionText>");
            strXML.append("<optionValue>-1</optionValue>");
            strXML.append("</entry>");
             rs.beforeFirst();
             while(rs.next())
             {
              strXML.append("<entry>");
            strXML.append("<optionText>"+rs.getString(2)+"</optionText>");
            strXML.append("<optionValue>"+rs.getString(1)+"</optionValue>");
            strXML.append("</entry>");
             }
             }
             strXML.append("</selectChoice>");
         response.setContentType("text/xml");  //注意這句話很重要,不能少
         PrintWriter out2= response.getWriter();//注意這句話很重要,不能少
         out2.write(strXML.toString());            //out.write();來返回XML文檔
         out2.close();
    %>
  </body>
</html>

net.js
/*
url-loading object and a request queue built on top of it
*/

/* namespacing object */
var net=new Object();

net.READY_STATE_UNINITIALIZED=0;
net.READY_STATE_LOADING=1;
net.READY_STATE_LOADED=2;
net.READY_STATE_INTERACTIVE=3;
net.READY_STATE_COMPLETE=4;

/*--- content loader object for cross-browser requests ---*/
net.ContentLoader=function(url,onload,onerror,method,params,contentType){
  this.req=null;
  this.onload=onload;
  this.onerror=(onerror) ? onerror : this.defaultError;
  this.loadXMLDoc(url,method,params,contentType);
}

net.ContentLoader.prototype.loadXMLDoc=function(url,method,params,contentType){
  if (!method){
    method="GET";
  }
  if (!contentType && method=="POST"){
    contentType=&apos;application/x-www-form-urlencoded&apos;;
  }
  if (window.XMLHttpRequest){
    this.req=new XMLHttpRequest();
  } else if (window.ActiveXObject){
    this.req=new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (this.req){
    try{
      var loader=this;
      this.req.onreadystatechange=function(){
        net.ContentLoader.onReadyState.call(loader);
      }
      this.req.open(method,url,true);
      if (contentType){
        this.req.setRequestHeader(&apos;Content-Type&apos;, contentType);
      }
      this.req.send(params);
    }catch (err){
      this.onerror.call(this);
    }
  }
}

net.ContentLoader.onReadyState=function(){
  var req=this.req;
  var ready=req.readyState;
  if (ready==net.READY_STATE_COMPLETE){
    var httpStatus=req.status;
    if (httpStatus==200 || httpStatus==0){
      this.onload.call(this);
    }else{
      this.onerror.call(this);
    }
  }
}

net.ContentLoader.prototype.defaultError=function(){
  alert("error fetching data!"
    +"/n/nreadyState:"+this.req.readyState
    +"/nstatus: "+this.req.status
    +"/nheaders: "+this.req.getAllResponseHeaders());
}

 

附件:csdn空間/ ajax動態雙組合.txt

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.