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?
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>
Hmm, é algo assim (não mexo nisso desde inicio de 94):
R
raphaelpaiva
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
D
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. O responseText conterá a sua tag select mais os options.
<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%><%Stringpath=request.getContextPath();StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPEHTMLPUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><basehref="<%=basePath%>"><title>MyJSP'Teste.jsp'startingpage</title><metahttp-equiv="pragma"content="no-cache"><metahttp-equiv="cache-control"content="no-cache"><metahttp-equiv="expires"content="0"><metahttp-equiv="keywords"content="keyword1,keyword2,keyword3"><metahttp-equiv="description"content="This is my page"><scriptlanguage="JavaScript">vartXHR=0;functionXMLHTTPRequest(){if(window.XMLHttpRequest){a=newXMLHttpRequest();}//Objeto nativo (FF/Safari/Opera7.6+)else{try{a=newActiveXObject("Msxml2.XMLHTTP");//activeX (IE5.5+/MSXML2+)}catch(e){try{a=newActiveXObject("Microsoft.XMLHTTP");//activeX (IE5+/MSXML1)}catch(e){/* O navegador não tem suporte */a=false;}}}returna;}functionatualizaCidades(){varpEstado=document.Teste.Estado.options[document.Teste.Estado.selectedIndex].value;tXHR=XMLHTTPRequest();if(tXHR){document.Teste.Cidades.length=0;document.Teste.Cidades.options[0]=newOption("Aguarde....","");tXHR.open("GET","servlet/Teste?Estado="+pEstado,true);tXHR.onreadystatechange=recebeResultado;tXHR.send(null);}}functionrecebeResultado(){if(!tXHR){returnfalse;}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><formname="Teste">Estados:<selectname="Estado"onChange="atualizaCidades()"><optionvalue="AC">AC</option><optionvalue="AL">AL</option><optionvalue="AM">AM</option><optionvalue="AP">AP</option><optionvalue="BA">BA</option><optionvalue="CE">CE</option><optionvalue="DF">DF</option><optionvalue="ES">ES</option><optionvalue="GO">GO</option><optionvalue="MA">MA</option><optionvalue="MG">MG</option><optionvalue="MS">MS</option><optionvalue="MT">MT</option><optionvalue="PB">PB</option><optionvalue="PE">PE</option><optionvalue="PI">PI</option><optionvalue="PR">PR</option><optionvalue="RJ">RJ</option><optionvalue="RO">RO</option><optionvalue="RN">RN</option><optionvalue="RR">RR</option><optionvalue="RS">RS</option><optionvalue="SC">SC</option><optionvalue="SE">SE</option><optionvalue="SP">SP</option><optionvalue="TO">TO</option></select><br>Cidades: <labelid="idCidades"><selectname="Cidades"><optionvalue=""></option></select></label></form></body></html>
Servlet
packagebr.com.juliano;importjava.io.IOException;importjava.io.PrintWriter;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.PreparedStatement;importjava.sql.ResultSet;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;publicclassTesteextendsHttpServlet{/** * */privatestaticfinallongserialVersionUID=1L;/** * Constructor of the object. */publicTeste(){super();}/** * Destruction of the servlet. <br> */publicvoiddestroy(){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 */publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{response.setContentType("text/html");Stringestado=request.getParameter("Estado");StringBufferretorno=newStringBuffer("");PrintWriterout=response.getWriter();out.println("<select name=\"Cidades\">");Connectionconn=null;try{Class.forName("oracle.jdbc.driver.OracleDriver");conn=DriverManager.getConnection("string conexão jdbc","conta","senha");Stringsql="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 ";PreparedStatementpreparedStatement=conn.prepareStatement(sql);ResultSetrs=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(Exceptionex){thrownewServletException("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 */publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{response.setContentType("text/html");PrintWriterout=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 */publicvoidinit()throwsServletException{// Put your code here}}
A lógica de funcionamento está nos arquivos acima, espero ter ajudado.
P
plentz
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)
}