客户端 jsp文件
<select id="province" name="province">
<option value="">请选择省份...</option>
</select>
<select id="city" name="city">
<option value="">请选择城市...</option>
</select>
javascript代码
function ajaxFunction(){
var xmlHttp;
try{ //Firefox
xmlHttp = new XMLHttpRequest();
}catch(e){
try{ //IE
xmlHttp = new ActiveXObject("Msxm12.XMLHTTP");
}catch(e){
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){}
}
}
return xmlHttp;
}
window.onload = function(){
//获取xmlhttpRequest对象
var xmlReq = ajaxFunction();
//处理服务器的响应 ,实时监听
xmlReq.onreadystatechange = function(){
//alert(xmlReq.status);
if(xmlReq.readyState == 4){ //响应发送完毕
if(xmlReq.status == 200 || xmlReq.status == 304){
var xmlDoc = xmlReq.responseXML;
var provinceElements = xmlDoc.getElementsByTagName("province");
//alert(provinceElements.length);
for(var i=0;i<provinceElements.length;i++){
var provinceElement = provinceElements[i];
var attrName = provinceElement.getAttribute("name");
var optionElement = document.createElement("option");
optionElement.setAttribute("value",attrName);
var textElement = document.createTextNode(attrName);
optionElement.appendChild(textElement);
var provinceElement = document.getElementById("province");
provinceElement.appendChild(optionElement);
}
}
}
}
//打开和服务器的链接
xmlReq.open("post","./TestServlet",true); //url.....
xmlReq.setRequestHeader("content-type","application/x-www-form-urlencoded");
//发送服务 get请求不会发送任何数据
xmlReq.send(null);
}
服务器端 生成xml 文件
package myDemo;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/xml;charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<china>");
out.println("<province name='湖南省'>");
out.println("<city>长沙</city>");
out.println("<city>郴州</city>");
out.println("<city>岳阳</city>");
out.println("<city>株洲</city>");
out.println("</province>");
out.println("<province name='广东省'>");
out.println("<city>广州</city>");
out.println("<city>深圳</city>");
out.println("<city>惠州</city>");
out.println("<city>东莞</city>");
out.println("</province>");
out.println("</china>");
}
}
原文链接:https://www.f2er.com/ajax/165498.html