ajax 二級聯動示例

    最近研究一下ajax和<html>互動 ^_^  感覺還真是不錯

 

 

首先創建兩個實體類 get set方法

 

 

國家

public class Country implements Serializable{
 
   private static final Long serialVersionUID=123456789098765432L;
  
   private Long id;
  
   private String name;

   private Set<City>  city=new HashSet<City>(0);

城市

public class City implements Serializable{
   
  private static final long serialVersionUID=-250998437593347316L;
  
  private Long id;
 
  private String name;

     private Country  country; 

 

一對多關係  持久層 用hibernate 這裏就不多說了

 

 

 

兩個類要和ActionForm放在同個包下

 

 

 

 

ActionForm

 

public class RegisterForm extends ActionForm {
      /**
  *
  */
 

 private Country country=new Country();
 

    
 public Collection<Country> getCountrys(){
  List<Country> list=new ArrayList<Country>();
  Show  show=new ShowImpl();
        list=show.show();
 
  
  return list;
 }
 
}

 

 

然後是action了

 

 

public class OpentionAction extends MappingDispatchAction {


 public ActionForward toAjax(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
  RegisterForm  reForm=(RegisterForm)form;  
        return mapping.findForward("toAjax");
 }

 

還有servlet

 

  public class SelectServlet extends HttpServlet{

  private static final long serialVersionUID = 1L;

     public SelectServlet()
     {
         super();
     }

     public void destroy()
     {
         super.destroy();
     }

     public void doGet(HttpServletRequest request, HttpServletResponse response)
             throws ServletException, IOException
     {
//         response.setCharacterEncoding("GBK");
         response.setContentType("text/xml");
         response.setHeader("Cache-Control", "no-cache");
         request.setCharacterEncoding("GBK");
         response.setCharacterEncoding("UTF-8");
         String targetId =request.getParameter("id").toString();
         System.out.println("haha"+targetId);
         // 獲得請求中參數爲id的值
         String xml_start = "<selects>";
         String xml_end = "</selects>";
         String xml = "";
         Show  show=new ShowImpl();
         

            List<City>    list1=show.show2();
         Iterator   it1=list1.iterator();


             while(it1.hasNext()){
              
   
           City city=(City)it1.next();
            

  System.out.println("haha"+city.getCountry().getId().toString());
             

 if(city.getCountry().getId().toString().equalsIgnoreCase(targetId)){
              xml +="<select><value>"+city.getId()+"</value><text>"+city.getName()+"</text></select>";
              }
              
             }   
         if (targetId.endsWith("0"))
         {
             xml = "<select><value>0</value><text>請選擇</text></select>";
         }

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

     public void init() throws ServletException
     {
     }
 
 }

下面是頁面了index.jsp

中寫一個<a href ="ajax.do">ajax</a>

ajax.jsp

<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage=""%>
<
%@taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<
%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<
%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>

<html>
    <head>
        <title>二級菜單聯動演示</title>
        <script type="text/javascript">
    var req;
    window.οnlοad=function()
    {//頁面加載時的函數
    }
  
    function Change_Select(){//當第一個下拉框的選項發生改變時調用該函數
      var province = document.getElementById('country.name').value;
      var url = "select?id="+ escape(province);
      if(window.XMLHttpRequest){
        req = new XMLHttpRequest();
      }else if(window.ActiveXObject){
        req = new ActiveXObject("Microsoft.XMLHTTP");
      }
      if(req){
        req.open("GET",url,true);
         //指定回調函數爲callback
        req.onreadystatechange = callback;
        req.send(null);
      }
    }
    //回調函數
    function callback(){
      if(req.readyState ==4){//4爲返回
        if(req.status ==200){//200爲完成
          parseMessage();//解析XML文檔
        }else{
          alert("不能得到描述信息:" + req.statusText);
        }
      }
    }
    //解析返回xml的方法
    function parseMessage(){
      var xmlDoc = req.responseXML.documentElement;//獲得返回的XML文檔
      var xSel = xmlDoc.getElementsByTagName('select');
      //獲得XML文檔中的所有<select>標記
      var select_root = document.getElementById('city');
      //獲得網頁中的第二個下拉框
      select_root.options.length=0;
      //每次獲得新的數據的時候先把每二個下拉框架的長度清0
    
      for(var i=0;i<xSel.length;i++){
        var xValue = xSel[i].childNodes[0].firstChild.nodeValue;
        //獲得每個<select>標記中的第一個標記的值,也就是<value>標記的值
        var xText = xSel[i].childNodes[1].firstChild.nodeValue;
        //獲得每個<select>標記中的第二個標記的值,也就是<text>標記的值
      
        var option = new Option(xText, xValue);
        //根據每組value和text標記的值創建一個option對象
      
        try{
          select_root.add(option);//將option對象添加到第二個下拉框中
        }catch(e){
        }
      }
    }      
  </script>
    </head>

    <body>
        <div align="center">
            <html:form>
                <table width="70%" border="0" cellspacing="0" cellpadding="0">
                    <tr>
                        <td align="center">
                            二級聯動示例
                        </td>
                    </tr>
                    <tr>
                        <td>
         <html:select property="country.name" οnchange="Change_Select()">
                               <option value="0">
                                    請選擇
                                </option>
           <html:optionsCollection property="countrys" label="name" value="id" />
        </html:select>
                            <select name="city" id="city">
                                <!--第二個下拉菜單-->
                                <option value="0">
                                    請選擇
                                </option>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td>
                        </td>
                    <tr>
                </table>
            </html:form>
        </div>
    </body>
</html>

<struts-config>
  
  <form-beans>
      <form-bean name="registerForm" type="form.RegisterForm"/>
  </form-beans>
 
  <action-mappings>  
        
    <action path="/ajax" type="action.OpentionAction"
           name="registerForm" parameter="toAjax" scope="request" >
      <forward name="toAjax" path="/ajax.jsp"/>
    </action>      
   </action-mappings>
 
  <!-- message-resources parameter="com.tarena.struts.message.MessageResources"/ -->
 
</struts-config>

web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="
http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">
    <servlet>   
    <servlet-name>ActionServlet</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet> 
  <servlet>
        <servlet-name>SelectServlet</servlet-name>
        <servlet-class>com.SelectServlet</servlet-class>
  </servlet>      
  <servlet-mapping> 
    <servlet-name>ActionServlet</servlet-name>
    <url-pattern>*.do</url-pattern>     
  </servlet-mapping>
   <servlet-mapping>
        <servlet-name>SelectServlet</servlet-name>
        <url-pattern>/select</url-pattern>
    </servlet-mapping> 
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 strus-config.xml
發佈了17 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章