Não consigo carregar as cidades de acordo com os estado selecionados…
Segue codigo completo que estou fazendo…
cadastro.jsp
<html>
<head>
<title>Exemplo Ajax</title>
</head>
<script type="text/javascript">
var request;
function sendRequest(){
//Determina o Estado selecionado
combo = document.getElementById("estado");
estado = combo.options[combo.selectedIndex].value;
//Retorna quando nenhum Estado for selecionado
if(estado == '-1')
return;
//Monta a url de requisição para o servidor
//alert("estado " +estado);
url = "cadastrarCliente?action=preencherCidades&estado="+estado;
//Inicializa o objeto XMLHttpRequest para o Mozilla
if(window.XMLHttpRequest){
alert("Mozilla");
request = new XMLHttpRequest();
}
//Inicializa o objeto XMLHttpRequest para o Internet Explorer
else if (window.ActiveXObject){
alert("Explorer");
request = new ActiveXObject("Microsoft.XMLHTTP");
}
//determina a função para o processamento da requisição
request.onreadystatechange= processRequest;
//configura a requisição
request.open("GET", url, true);
//envia a requisição
request.send(null);
}
function processRequest(){
//Verifica se a resposta já foi recebida por completo
if (request.readyState ==4){
//Verifica se o status é OK
if (request.status==200){
//Faz a leitura do documento XML recebido
var response = request.responseXML;
var raiz = response.getElementsByTagName("cidades").item(0);
var cidades = raiz.getElementsByTagName("cidade");
//alert("cidades" + cidades);
//Seleciona a caixa de seleção de cidades
var selectNode = document.getElementById("cidade");
//Apaga as opções atuais de seleção
selectNode.options.length = 0;
//preenche a caixa de opções com os valores recebidos
for(var i =0; i < cidades.length ; i++){
var txtCidade = cidades.item(i).firstChild.data;
var option = new Option(txtCidade);
selectNode.add(option,null);
//alert("txtCidade" + txtCidade);
}
}
}
}
</script>
<body>
<h1>Cadastro de Cliente</h1>
<form action='<%=request.getContextPath() +"/cadastrarCliente"%>' method='post'>
<fieldset><legend>Dados do Cliente</legend>
<table>
<tr>
<td><label for="nome">Nome:</label></td>
<td colspan="3">
<input name="nome" id="nome" type="text" size="75" maxlength="255"></input>
</td>
</tr>
<tr>
<td><label for="telefone">Telefone (0000-0000):</label>
</td>
<td><input name="telefone" id="telefone" type="text" size="16"></input>
</td>
<td><label for='email'>e-mail:</label>
</td>
<td><input name="email" id="email" type="text" size="37"></input>
</td>
</tr>
</table>
</fieldset>
<fieldset>
<legend></legend>
<table>
<tr>
<td><label for="endereco">Rua/Av:</label></td>
<td><input name="rua" id="rua" type="text" size="40" maxlength="255"></input>
</td>
<td><label for="numero">Número:</label></td>
<td><input name="numero" id="numero" type="text" size="8" maxlength="5"></input>
</td>
</tr>
<tr>
<td><label for="bairro">Bairro:</label></td>
<td><input name="bairro" id="bairro" type="text"></input>
</td>
<td><label for='cep'>Cep (00000-000):</label>
</td>
<td><input name="cep" id="cep" type="text" size="8"></input>
</td>
</tr>
<tr>
<td><label for="estado">Estado:</label></td>
<td>
<select name="estado" id="estado" onchange="sendRequest();">
<option value='-1'>Escolha um Estado</option>
<option value='MG'>MG</option>
<option value='SP'>SP</option>
<option value='RJ'>RJ</option>
</select>
</td>
<td><label for="cidade">Cidade:</label>
</td>
<td><select name="cidade" id="cidade" style="width: 200px"></select>
</td>
</tr>
</table>
</fieldset>
<input type="submit" value="Salvar"></input>
</form>
</body>
</html>
cadastrarCliente.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class cadastrarCliente extends HttpServlet {
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String action = request.getParameter("action");
if("preencherCidades".equals(action)){
String estado = request.getParameter("estado");
//Leitura da Lista de cidade do BD
List cidades = ClientesDAO.getInstance().getCidades(estado);
if(cidades.size()>0){
System.out.println(response);
response.setContentType("text/xml");
PrintWriter out = response.getWriter();
out.write("<?xml version='1.0' ?>");
out.write("<cidades>");
for(Iterator it = cidades.iterator();it.hasNext();){
Object elem = (Object)it.next();
out.write("<cidade>"+elem+"</cidade>");
System.out.println(elem);
}
out.write("</cidades>");
System.out.println(out);
}
} else{
//Codigo para cadastro do Cliente
}
System.out.println("Finalizando Servlet");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
processRequest(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
processRequest(request,response);
}
}
ClientesDao.java
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ClientesDAO {
public static ClientesDAO instance = new ClientesDAO();
private Map bancoDados;
private ClientesDAO(){
bancoDados = new HashMap();
bancoDados.put("MG", new String[]{"Belo Horizonte","Uberaba","Uberlandia"});
bancoDados.put("RJ", new String[]{"Buzios","Cabo Frio","Rio de Janeiro"});
bancoDados.put("SP", new String[]{"Sao Paulo","Santos","Campinas"});
}
public static ClientesDAO getInstance(){
return instance;
}
public List getCidades(String estado){
String[] cidades = (String[]) bancoDados.get(estado);
return Arrays.asList(cidades);
}
}