Ajax實現三級聯動

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" οnchange="getSerie()">
  <option value="0">--請選擇汽車品牌--</option>
  <c:forEach items="${list }" var="carBand">
  <option value="${carBand.id }">${carBand.name }</option>
  </c:forEach>
  </select>
  <select id="carSerie" οnchange="getModel()">
  <option value="0">--請選擇汽車系列--</option>
  </select>
  <select id="carModel">
  <option value="0">--請選擇汽車型號--</option>
  </select>
  <button id="submit">確定</button>

後臺用servlet的話,獲取參數用request.getParamter("參數名")就能獲得參數值了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章