您的位置:首页 > 其它

Ajax实现三级联动

2014-03-13 20:18 197 查看
Ajax代码:

<script type="text/javascript">

//根据选择的汽车品牌来自动填充汽车型号的下拉列表

function getSerie(){

var xhr;

if(window.XMLHttpRequest){

xhr = new XMLHttpRequest();

}else{

xhr = new ActiveXObject("Microsoft.XMLHTTP");

}

xhr.onreadystatechange=function(){

if(xhr.readyState==4 && xhr.status==200){

var carSerie = document.getElementById("carSerie");

var serieIdAndName = xhr.responseText;

var series = serieIdAndName.split(",");

clearSelect("carSerie");

for(var i = 0;i<series.length-1;i=i+2){

carSerie.options[carSerie.length]=new Option(series[i+1],series[i]);

}

}

}

xhr.open("GET","${pageContext.request.contextPath}/servlet/AllCarServlet?brandId="+document.getElementById("carBand").value,true);

xhr.send();

}

//根据选择的汽车系列来填充车型的下拉列表

function getModel(){

var xhr;

if(window.XMLHttpRequest){

xhr = new XMLHttpRequest();

}else{

xhr = new ActiveXObject("Microsoft.XMLHTTP");

}

xhr.onreadystatechange=function(){

if(xhr.readyState==4 && xhr.status==200){

var carModel = document.getElementById("carModel");

var modelIdAndName = xhr.responseText;

var models = modelIdAndName.split(",");

clearSelect("carModel");

for(var i = 0;i<models.length-1;i=i+2){

carModel.options[carModel.length]=new Option(models[i+1],models[i]);

}

}

}

xhr.open("GET","${pageContext.request.contextPath}/servlet/AllCarServlet?serieId="+document.getElementById("carSerie").value,true);

xhr.send();

}

//清空下拉列表

function clearSelect(id){

var select = document.getElementById(id);

select.options.length = 0;

select.options[0] = new Option("--请选择车系--","0");

var select = document.getElementById("carModel");

select.options.length = 0;

select.options[0] = new Option("--请选择车型--","0");

}

$(function(){

$("#submit").click(function(){

var mId = $("#carModel").val();

window.location.href="${pageContext.request.contextPath}/servlet/ShowCarModelDetailServlet?id="+mId;

});

});

</script>

html代码:

<select id="carBand" onchange="getSerie()">

<option value="0">--请选择汽车品牌--</option>

<c:forEach items="${list }" var="carBand">

<option value="${carBand.id }">${carBand.name }</option>

</c:forEach>

</select>

<select id="carSerie" onchange="getModel()">

<option value="0">--请选择汽车系列--</option>

</select>

<select id="carModel">

<option value="0">--请选择汽车型号--</option>

</select>

<button id="submit">确定</button>

后台用servlet的话,获取参数用request.getParamter("参数名")就能获得参数值了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: