日期:2014-05-16  浏览次数:20373 次

ajax jsp 级联菜单(原始方式)
public class ProvLoad extends HttpServlet {
    Ajax001 a1=new Ajax001();
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
        List<String> prolist=a1.loadPro();
        StringBuffer sb=new StringBuffer("[");
        for(int i=0;i<prolist.size();i++){
        	sb.append(prolist.get(i));
        	if(i<prolist.size()-1){
        	sb.append(",");	
        	}
        }
        sb.append("]");
        response.setContentType("text/json; charset=utf-8");
		response.getWriter().println(sb.toString());
	}

}

?ajax js文件

function   createXmlHttpRequest(){
var xmlhttp = null;
try{
		//Firefox, Opera 8.0+, Safari
           xmlhttp=new XMLHttpRequest();
		}catch(e){//IEIE7.0以下的浏览器以ActiveX组件的方式来创建XMLHttpRequest对象
var MSXML = 
['MSXML2.XMLHTTP.6.0','MSXML2.XMLHTTP.5.0',
'MSXML2.XMLHTTP.4.0','MSXML2.XMLHTTP.3.0',
'MSXML2.XMLHTTP','Microsoft.XMLHTTP'];
  for(var n = 0; n < MSXML.length; n ++){
    try{
      xmlhttp = new ActiveXObject(MSXML[n]);
      break;
    }catch(e){}}
  }
return xmlhttp;
}
function loadcity(name){
	var xhr=createXmlHttpRequest();
	xhr.onreadystatechange=function(){
		if(xhr.readyState==4 ||(xhr.status==200 || xhr.status==304)){
			alert(xhr.responseText);
			var ret=eval("("+xhr.responseText+")");
			alert("ret lenght:"+ret.length);
			var v="";
			for(var i=0;i<ret.length;i++){
			//	alert("retX="+ret[i]);
				v+="<option>"+ret[i]+"</option>";
			}
			//alert("v:"+v);
			document.getElementById("city").innerHTML=v;
		}
	}
	xhr.open("post","servlet/CityLoad",true);
	xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	alert(name);
	xhr.send("name="+name);
}
function loadpro(){
	var xhr=createXmlHttpRequest();
	xhr.onreadystatechange=function(){
		if(xhr.readyState==4 ||(xhr.status==200 || xhr.status==304)){
			var ret=eval("("+xhr.responseText+")");
			var s="<option>--</option>";
			for(var i=0;i<ret.length;i++){
				s+="<option>"+ret[i]+"</option>";
			}
			document.getElementById("pro").innerHTML=s;
		}
	}
	xhr.open("get","servlet/ProvLoad",true);
	xhr.send(null);
}
window.onload=loadpro;

?

页面内容

  选择省份<select id="pro" onchange="loadcity(this.value)"></select>选择城市<select id="city"></select>

?