Visualizzazione dei risultati da 1 a 6 su 6
  1. #1

    Select dinamiche in ajax

    http://forum.html.it/forum/showthrea...9#post10636749

    seguendo la falsa riga di questo post vorrei fare un'analoga versione in java... ci sto provando ma pecco di esperienza. vi dico quello che ho fatto.

    Ho un db access: tabella provincia(pro_vin_cd,pro_vin_ds) e la tabella termunicipal(provincia,termino,descripcion).

    2 select box: provincia e comune.

    il progettino è il classico java project...

    web.xml

    codice:
    <?xml version="1.0" encoding="ISO-8859-1"?>
    
    <!DOCTYPE web-app
        PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
        "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
    
     <web-app>
     <servlet>
      <servlet-name>getComune</servlet-name> 
      <servlet-class>pkg.Getcomune</servlet-class> 
     </servlet>
     <servlet-mapping>
      <servlet-name>getComune</servlet-name> 
      <url-pattern>*.getComune</url-pattern>
     </servlet-mapping>
      <welcome-file-list>
        <welcome-file>main.jsp</welcome-file>
     </welcome-file-list>
    </web-app>
    main.jsp

    codice:
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
        
    <% 
    
    
    
    List provincia = new ArrayList();
    
    
    try{
    	
    	Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        String filename = "C:\\Documents and Settings\\minicgag\\Desktop\\miei scripts\\Database Venditori\\Database_Venditori.mdb";
        //String filename = "D:\\JONAS_4_8_4\\webapps\\autoload\\callc\\registrochiamate.mdb";
        String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
        database+= filename.trim() + ";DriverID=22;READONLY=true}"; // add on to the end 
        // now we can get the connection from the DriverManager
        Connection con = DriverManager.getConnection( database ,"",""); 
        Statement s = con.createStatement();
        
        String query1 = "select * from provincia where attivo = 'si'";
        
        s.execute(query1);
        ResultSet rs = s.getResultSet();
        if(rs!=null){
    	    while(rs.next()){
    	    	provincia.add(rs.getString(1));
    	    	provincia.add(rs.getString(2));
    	    	
    	    }
        }
        	
    	
        
        con.close(); // close the Connection to let the database know we're done with it
        s.close();
    	
        
        
    	
    	
    
    }
    catch(Exception e){
    	e.printStackTrace();
    }
    finally{
    	try {
    		
    	} 
    	catch (Exception e) {
    		e.printStackTrace();
    	}
    }
    %>
    
    
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <%@page import = "java.util.ArrayList" %>
    <%@page import = "java.util.List" %>
    <%@page import = "java.sql.*" %>
    
    
    
    <script language="javascript" type="text/javascript">
    <!--
    var http = createRequestObject(); 
    var where = (navigator.appName == "Microsoft Internet Explorer") ? -1 : null; 
    
    function createRequestObject() { 
         var ro; 
         var browser = navigator.appName; 
         if(browser == "Microsoft Internet Explorer"){ 
              ro = new ActiveXObject("Microsoft.XMLHTTP"); 
         }else{ 
              ro = new XMLHttpRequest(); 
         } 
         return ro; 
    } 
    
    function addElement(ogg,val,text){ 
      var newOption; 
      newOption = document.createElement("option"); 
      newOption.value = val; 
      newOption.text = text; 
      ogg.add(newOption, where);     
    } 
    
    function removeElement(ogg){ 
      if(ogg.options.length > 0){ 
        while (ogg.options.length) { 
          ogg.remove(0); 
        }     
      } 
    } 
    
    function disabledElement(ogg,val){ 
      document.getElementById(ogg).disabled = val; 
    } 
    
    function loadingProvince(oggId){ 
      var id = document.getElementById(oggId).value; 
      http.open('GET','do.getComune?prov='+id, true); 
      http.onreadystatechange = getComune; 
      http.send(null);   
    } 
    
    function getComune(){ 
      var State = document.getElementById('l2'); 
      removeElement(State); 
      id = document.getElementById('Select_provincia').value; 
      if(id == 'sel'){ 
        disabledElement('l2',true); 
        addElement(State,'sel','Seleziona prima un Continente:'); 
      }else{ 
        if(http.readyState == 4){ 
          if (http.status == 200) { 
               var response = http.responseText; 
            if(response == ''){ 
              disabledElement('l2',true); 
              addElement(State,'sel','nessun comune presente'); 
            }else{ 
              removeElement(State); 
              coppia = response.split(','); 
              max = coppia.length; 
              addElement(State,'sel','seleziona un comune:'); 
              for(x=0;x<max;x++){ 
                val = coppia[x].split('-'); 
                addElement(State,val[0],val[1]); 
              } 
              disabledElement('l2',false); 
            } 
             } 
        }else{ 
          addElement(State,'sel','Loading...'); 
        } 
      } 
      
    } 
    
    
    
    //-->
    </script>
    
    
    
    </head>
    
                
        <form name="form">
        	<div id="content"> 
    		  <div id="label1"> 
    		    Select 1 
    		  </div> 
    		  <div id="select1"> 
    		    <select id="Select_provincia" name="Select_provincia" onchange="loadingProvince('Select_provincia')" >
                        <%for(int i=0;i<provincia.size();i=i+2){ %>
                        <option <%if(provincia.get(i+1)=="Milano"){%> selected="selected" <%}%> value="<%=provincia.get(i) %>"><%=provincia.get(i+1) %></option>
                        <%} %>
                    </select>
    		  </div> 
    		  <div id="label2"> 
    		    Select 2 
    		  </div> 
    		  <div id="select2"> 
    		    <select name="l2" id="l2" onChange="loadingCity('l2')" disabled> 
    		    <option value="sel" selected="selected">Seleziona un comune:</option> 
    		    </select>   
    		  </div>   
    		     
    		</div> 
        	
        </form>
    </body>
    </html>

    la servlet Getcomune.java

    codice:
    package pkg;
    
    import java.io.IOException;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class Getcomune extends HttpServlet{
    	
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
    	String prov=null;
    	ResultSet rs=null;
    	
    
    	public void init(ServletConfig config) throws ServletException {
    	    // Always call super.init(config) first  (servlet mantra #1)
    	    super.init(config);
    	    	    	    
    	}
    	
    	public void doGet(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
    		
    		res.setContentType("text/html");
    		
    		prov = req.getParameter("prov");
    		
    		try{
    		    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    		    String filename = "C:\\Documents and Settings\\minicgag\\Desktop\\miei scripts\\Database Venditori\\Database_Venditori.mdb";
    		    //String filename = "D:\\JONAS_4_8_4\\webapps\\autoload\\callc\\registrochiamate.mdb";
    	        String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
    	        database+= filename.trim() + ";DriverID=22;READONLY=true}"; // add on to the end 
    	        // now we can get the connection from the DriverManager
    	        Connection con = DriverManager.getConnection( database ,"",""); 
    	        Statement s = con.createStatement();
    	        String query = "select termunicipal.termino, termunicipal.descripcion from termunicipal " +
    	        		"where termunicipal.provincia='"+prov+"'";
    	        
    	        
    	        System.out.println(query);
    	        s.execute(query);
    	        rs = s.getResultSet();
    	        
    	        if (rs != null) {// if rs == null, then there is no ResultSet to view
    	            while ( rs.next() ){ // this will step through our data row-by-row
    	    				
    	            	
    	                
    	            }
    	        }
    	        
    	        
    	        s.close(); // close the Statement to let the database know we're done with it
    	        con.close(); // close the Connection to let the database know we're done with it
    	       
    	        
    			}
    		catch(Exception e){System.out.println("ERROR: " + e);}
    		
    		
    				
    		req.getRequestDispatcher("main.jsp").forward(req, res);
    		
    	}
    	
    	public void destroy() {
    		
    	}
    
    }

    manca qualcosa...... come passo i risultati della servlet, indietro alla jsp per permettere alla form di visualizzarli???

    dopodichè direi che il tutto funziona...
    per qualsiasi dettaglio chiedete pure..

    grazie a tutti

    Nick

  2. #2
    riformulo la domanda
    come faccio, dopo che ho eseguito la servlet... quindi la query nella tabella dei comuni, a restituire i risultati alla jsp?


  3. #3
    Non ho letto tutto il codice ma immagino che tu voglia caricare automaticamente la combo con i comuni in base all'elemento selezionato nella combo delle province. Sbaglio?

    Se è così, il tuo approccio è leggermente sbagliato. Ajax viene utilizzato proprio per evitare il ricaricamento della pagina web, pertanto quando la servlet che richiami ha terminato il suo lavoro non devi eseguire un forward verso la stessa pagina, ma devi semplicemente "scrivere" il testo che vuoi sia inviato come risposta al browser. Questo testo di ritorno altro non è che la select dei comuni. Quindi è la servlet che genera il codice per visualizzare la combobox. Ad esempio:

    codice:
    String responseText = "";
    //generi il contenuto della combobox... Supponiamo che viene fouri la seguente stringa:
    responseText = <select name=\"comuni\">"+
                          "<option value=\"val1\">Comune1</option>"+
                          "<option value=\"val2\">Comune2</option>"+
                         "</select>";
    PrintWriter out = response.getWriter();
    out.println(responseText);
    out.close();
    Ora supponendo che la tua combobox dei comuni sia racchiusa in un <div id="div_comuni"></div> nella funzione javascript che esegui al termine della servelt ti basterà scrivere:

    codice:
    document.getElementById("div_comuni").innerHTML = http.responseText;
    Spero di essere stato chiaro e soprattutto di aver centrato il problema
    Al mio segnale... scatenate l'inferno!

  4. #4
    certo centri sempre il problema.... sono i miei primi passi con ajax quindi portato un po di pazienza

    dunque... ho modificato la servlet nel seguente modo

    codice:
    package pkg;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class Getcomune extends HttpServlet{
    	
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
    	String prov=null;
    	ResultSet rs=null;
    	String responseText = "";
    	
    
    	public void init(ServletConfig config) throws ServletException {
    	    // Always call super.init(config) first  (servlet mantra #1)
    	    super.init(config);
    	    	    	    
    	}
    	
    	public void doGet(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
    		
    		res.setContentType("text/html");
    		PrintWriter out = res.getWriter();
    		
    		prov = req.getParameter("prov");
    		
    		try{
    		    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    		    String filename = "C:\\Documents and Settings\\minicgag\\Desktop\\miei scripts\\Database Venditori\\Database_Venditori.mdb";
    		    //String filename = "D:\\JONAS_4_8_4\\webapps\\autoload\\callc\\registrochiamate.mdb";
    	        String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
    	        database+= filename.trim() + ";DriverID=22;READONLY=true}"; // add on to the end 
    	        // now we can get the connection from the DriverManager
    	        Connection con = DriverManager.getConnection( database ,"",""); 
    	        Statement s = con.createStatement();
    	        String query = "select termunicipal.termino, termunicipal.descripcion from termunicipal " +
    	        		"where termunicipal.provincia='"+prov+"'";
    	        
    	        
    	        System.out.println(query);
    	        s.execute(query);
    	        rs = s.getResultSet();
    	        responseText = "<select name=\"l2\" id=\"l2\" >";
    	        if (rs != null) {// if rs == null, then there is no ResultSet to view
    	            while ( rs.next() ){ // this will step through our data row-by-row
    	    				
    	            	responseText = responseText + 
                        	"<option value=\""+ rs.getString(1) +"\">"+rs.getString(2)+"</option>";
                        	
                       
    
    	                
    	            }
    	        }
    	        responseText = responseText + "</select>";
    	        
    	        s.close(); // close the Statement to let the database know we're done with it
    	        con.close(); // close the Connection to let the database know we're done with it
    	       
    	        System.out.println(responseText);
    	        
    	        
    	        out.println(responseText);
    	        out.close();
    
    			}
    		
    		
    		catch(Exception e){System.out.println("ERROR: " + e);}
    		
    		
    				
    		
    		
    	}
    	
    	public void destroy() {
    		
    	}
    
    }
    ...per ora mi fermo qui... senza mostrarti il file main.jsp (che è lo stesso per ora che ti ho mostrato nel post precedente)
    dico mi fermo qui in quanto facendomi stampare il responseText (System.out.println(responseText) non vedo nulla.

    potresti controllare se la servlet è sbagliata?

    intanto ti spiego come dovrebbe essere la select box. Semplicemente il value deve essere il codice comune e il testo deve essere il nome del comune

    grazie ancora R@ve...

  5. #5
    bene....
    grazie al prezioso aiuto di r@avem@ster abbiamo fatto la versione java delle select dinamiche.

    la servlet e il web xml sono quelli indicati prima. Il main.jsp va modificato nel seguente modo:

    codice:
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
        
    <% 
    
    
    
    List provincia = new ArrayList();
    
    
    try{
    	
    	Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        String filename = "C:\\Documents and Settings\\minicgag\\Desktop\\miei scripts\\Database Venditori\\Database_Venditori.mdb";
        //String filename = "D:\\JONAS_4_8_4\\webapps\\autoload\\callc\\registrochiamate.mdb";
        String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
        database+= filename.trim() + ";DriverID=22;READONLY=true}"; // add on to the end 
        // now we can get the connection from the DriverManager
        Connection con = DriverManager.getConnection( database ,"",""); 
        Statement s = con.createStatement();
        
        String query1 = "select * from provincia where attivo = 'si'";
        
        s.execute(query1);
        ResultSet rs = s.getResultSet();
        if(rs!=null){
    	    while(rs.next()){
    	    	provincia.add(rs.getString(1));
    	    	provincia.add(rs.getString(2));
    	    	
    	    }
        }
        	
    	
        
        con.close(); // close the Connection to let the database know we're done with it
        s.close();
    	
        
        
    	
    	
    
    }
    catch(Exception e){
    	e.printStackTrace();
    }
    finally{
    	try {
    		
    	} 
    	catch (Exception e) {
    		e.printStackTrace();
    	}
    }
    %>
    
    
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <%@page import = "java.util.ArrayList" %>
    <%@page import = "java.util.List" %>
    <%@page import = "java.sql.*" %>
    
    
    
    <script language="javascript" type="text/javascript">
    <!--
    var http = createRequestObject(); 
    var where = (navigator.appName == "Microsoft Internet Explorer") ? -1 : null; 
    
    function createRequestObject() { 
         var ro; 
         var browser = navigator.appName; 
         if(browser == "Microsoft Internet Explorer"){ 
              ro = new ActiveXObject("Microsoft.XMLHTTP"); 
         }else{ 
              ro = new XMLHttpRequest(); 
         } 
         return ro; 
    } 
    
    function addElement(ogg,val,text){ 
      var newOption; 
      newOption = document.createElement("option"); 
      newOption.value = val; 
      newOption.text = text; 
      ogg.add(newOption, where);     
    } 
    
    function removeElement(ogg){ 
      if(ogg.options.length > 0){ 
        while (ogg.options.length) { 
          ogg.remove(0); 
        }     
      } 
    } 
    
    function disabledElement(ogg,val){ 
      document.getElementById(ogg).disabled = val; 
    } 
    
    function loadingProvince(oggId){ 
      var id = document.getElementById(oggId).value; 
      http.open('GET','do.getComune?prov='+id, true); 
      http.onreadystatechange = getComune; 
      http.send(null);   
    } 
    
    function getComune(){ 
      var State = document.getElementById('l2'); 
      removeElement(State); 
      id = document.getElementById('Select_provincia').value; 
      if(id == 'sel'){ 
        disabledElement('l2',true); 
        addElement(State,'sel','Seleziona prima un Continente:'); 
      }else{ 
        if(http.readyState == 4){ 
          if (http.status == 200) { 
               var response = http.responseText; 
               document.getElementById("select2").innerHTML = response;
               
            
               disabledElement('l2',false); 
            } 
             
        }else{ 
          addElement(State,'sel','Loading...'); 
        } 
      } 
      
    } 
    
    
    
    //-->
    </script>
    
    
    
    </head>
    
                
        <form name="form">
        	<div id="content"> 
    		  <div id="label1"> 
    		    Select 1 
    		  </div> 
    		  <div id="select1"> 
    		    <select id="Select_provincia" name="Select_provincia" onchange="loadingProvince('Select_provincia')" >
                        <%for(int i=0;i<provincia.size();i=i+2){ %>
                        <option <%if(provincia.get(i+1)=="Milano"){%> selected="selected" <%}%> value="<%=provincia.get(i) %>"><%=provincia.get(i+1) %></option>
                        <%} %>
                    </select>
    		  </div> 
    		  <div id="label2"> 
    		    Select 2 
    		  </div> 
    		  <div id="select2"> 
    		    <select name="l2" id="l2" disabled> 
    		    <option value="sel" selected="selected">Seleziona un comune:</option> 
    		    </select>   
    		  </div>   
    		     
    		</div> 
        	
        </form>
    </body>
    </html>

    Spero di esservi stato di aiuto... per tutti quelli che come me, ci hanno sbattuto parecchio la testa


  6. #6
    Di nulla
    Al mio segnale... scatenate l'inferno!

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.