Modificando valores de combobox(select) com AJAX

Pessoal, estou utilizando AJAX e tenho uma dúvida que não encontrei exemplo que faça isso na web;
o que desejo fazer é “matar” o frame escondido que preenche um combo dependente de outro(por exemplo, combo de uf e combo de cidades).
já estou conseguindo trazer corretamente a string com os valores que devem ser colocados na outra combo, a string que retorno é da seguinte forma?

<option selected value='1'>Fortaleza</option>
<option value='2'>Sobral</option>
<option value='3'>Crato</option>

e etc…
com o frame esdondido, era feito de uma forma diferente da possível com AJAX…
Pois bem, minha aplicação retorna esta string para meu javascript, agora desejo coloca isso dentro do meu combo:
<select name=“cidades”> </select>

já tentei com o innerHTML, mas não funcionou…

Alguém tem alguma sugestão?

Obrigado

Hmm, é algo assim (não mexo nisso desde inicio de 94):

não tem uma forma em que eu possa passar o codigo html?

e dessa sua forma indicada, como eu coloco o valor selecionado?

obrigado

e se você colocar um DIV e o seu select dentro. Ao invés de atualizar somente as opções atualiza o select inteiro. O responseText conterá a sua tag select mais os options.

[code]
function processaMontaTrecho() {

if (req.readyState == 4) {
    if (req.status == 200) {
        div = window.opener.document.getElementById(campoRetorno);
        div.innerHTML = "";
        div.innerHTML = req.responseText;
        window.close();
     } else {
        alert("Ocorreu o seguinte erro recuperando os trechos:\n" + req.statusText);
     }
}

}[/code]

E acho melhor editar o DOM do select que modificar o html em sí. Um opção é você gerar o javascript no servidor e dar um eval nele.

Esse javascript no servidor faria o que então?

[quote=debersom]e se você colocar um DIV e o seu select dentro. Ao invés de atualizar somente as opções atualiza o select inteiro.
[/quote]
Boa sugestão… Pena que não posso utilizar este tipo de solução na aplicação…

Vou facilitar… :roll:

Alguem tem ou viu algum exemplo de combo que modifique os valores de outro?

Já tentou com o dojo?

http://www.devmedia.com.br/visualizacomponente.aspx?comp=1811&site=6

Segue um exemplo básico.

JSP

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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 'Teste.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">
    
    <script language="JavaScript">  
        var tXHR=0;

        function XMLHTTPRequest() {
          if (window.XMLHttpRequest) { 
              a=new XMLHttpRequest(); } //Objeto nativo (FF/Safari/Opera7.6+)
          else {
            try { 
               a=new ActiveXObject("Msxml2.XMLHTTP");  //activeX (IE5.5+/MSXML2+)
            }   
            catch(e) {
              try { 
                 a=new ActiveXObject("Microsoft.XMLHTTP"); //activeX (IE5+/MSXML1)
              }   
              catch(e) { /* O navegador não tem suporte */ 
                 a=false; 
              }
            }
          } 
          return a;
        }

        function atualizaCidades() {
            var pEstado = document.Teste.Estado.options[document.Teste.Estado.selectedIndex].value;
            tXHR=XMLHTTPRequest();
            if (tXHR) {
                document.Teste.Cidades.length = 0;
                document.Teste.Cidades.options[0] = new Option("Aguarde....","");
                tXHR.open("GET", "servlet/Teste?Estado="+pEstado, true);    
                tXHR.onreadystatechange=recebeResultado;
                tXHR.send(null);
            }
        }
        
        function recebeResultado() {
            if (!tXHR) {
                return false;
            }
            else {
                if (tXHR.readyState == 4) {             
                    if (tXHR.status == 200) {
                        document.getElementById("idCidades").innerHTML = tXHR.responseText;
                    }
                    else {
                        alert('Erro! "'+ tXHR.statusText +'" (erro '+ tXHR.status +')'); 
                    }
                }    
            }
        }
    </script>        
    
    
  </head>
  
  <body>
    <form name="Teste">
    Estados:
    <select name="Estado" onChange="atualizaCidades()">
        <option value="AC">AC</option> 
        <option value="AL">AL</option> 
        <option value="AM">AM</option> 
        <option value="AP">AP</option> 
        <option value="BA">BA</option> 
        <option value="CE">CE</option> 
        <option value="DF">DF</option> 
        <option value="ES">ES</option> 
        <option value="GO">GO</option> 
        <option value="MA">MA</option> 
        <option value="MG">MG</option> 
        <option value="MS">MS</option> 
        <option value="MT">MT</option> 
        <option value="PB">PB</option> 
        <option value="PE">PE</option> 
        <option value="PI">PI</option> 
        <option value="PR">PR</option> 
        <option value="RJ">RJ</option> 
        <option value="RO">RO</option> 
        <option value="RN">RN</option> 
        <option value="RR">RR</option> 
        <option value="RS">RS</option> 
        <option value="SC">SC</option> 
        <option value="SE">SE</option> 
        <option value="SP">SP</option> 
        <option value="TO">TO</option> 
    </select>
    <br>
    Cidades:&nbsp;<label id="idCidades"><select name="Cidades"><option value=""></option></select></label>
    </form>
  </body>
</html>

Servlet

package br.com.juliano;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Teste extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    /**
     * Constructor of the object.
     */
    public Teste() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        String estado = request.getParameter("Estado");
        StringBuffer retorno = new StringBuffer("");
        
        PrintWriter out = response.getWriter();
        out.println("<select name=\"Cidades\">");
        
        Connection conn = null;
        
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            conn = DriverManager.getConnection("string conexão jdbc","conta","senha");
            
            String sql = "select "
               + "   cid.idt_cidade, "
               + "   cid.nom_cidade "
               + " from "
               + "   pais pais, "
               + "   estado est, "
               + "   cidade cid "
               + " where "
               + "       cid.sig_pais=pais.sig_pais "
               + "   and cid.sig_estado=est.sig_estado (+) "
               + "   and cid.sig_pais=est.sig_pais (+) "       
               + "   and cid.sig_estado = '" + estado + "'"
               + " order by cid.nom_cidade ";
            
            PreparedStatement preparedStatement = conn.prepareStatement(sql);
            ResultSet rs = preparedStatement.executeQuery();
            while (rs.next()) {
                retorno.append("<option value=\""+rs.getString("IDT_CIDADE")+"\">"+rs.getString("NOM_CIDADE")+"</option>\n"); 
            }
            
            out.println(retorno);
            if (conn != null) {
                conn.close();
            }
        }
        catch (Exception ex) {
            throw new ServletException("Erro: "+ex);
        }
        out.println("</select>");
        out.flush();
        out.close();
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.print("    This is ");
        out.print(this.getClass());
        out.println(", using the POST method");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occure
     */
    public void init() throws ServletException {
        // Put your code here
    }

}

A lógica de funcionamento está nos arquivos acima, espero ter ajudado.

function addOptionToSelect(select, text, value) { var optionElm = document.createElement('option'); var optionText = document.createTextNode(text); if (value!='' && value!=null) optionElm.value = value; return select.appendChild(optionElm.appendChild(optionText).parentNode) }