ajax實現級聯下拉式功能表非常簡單,下面是一個用ajax實現的省市級聯的下拉式功能表;
jsp中在<select>中添加onchange事件,觸發該事件調用實現ajax的js:
<div><form action="Pcs" method="post">所在省:<select name="pro" id="pro" onchange="chCity();"><option>--請選擇--</option><option value="beijing">北京市</option><option value="shandong">山東省</option><option value="hebei">河北省</option> </select> 所在市:<select name="cit" id="cit"><option>--請選擇--</option> </select><br></form></div>
正常的下拉式功能表選項是在資料庫取出來的,為了方便,我把省直接寫在裡面;所在市除了“選擇”目前沒有實際的option;
js中實現ajax:
function chCity(){var pro=document.all("pro").value;if(window.XmlHttpRequest){xmlHttpRequest=new XmlHttpRequest();}else{xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP");}xmlHttpRequest.onreadystatechange=callBack;var url="Pcs";xmlHttpRequest.open("post",url,true);xmlHttpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");xmlHttpRequest.send("pro="+pro+"&timeStamp="+(new Date()).getTime());}//回呼函數function callBack(){if(xmlHttpRequest.readyState==4 && xmlHttpRequest.status==200){var result=xmlHttpRequest.responseText;result=result.replace(/(^\s*)|(\s*$)/g, "");var city=result.split("|");var citySelect=document.all("cit");for(var i=citySelect.options.length-1;i>=0;i--){citySelect.options.remove(i);}for(var i=0;i<city.length;i++){var vn=city[i].split(",");var cvalue=vn[0];var cname=vn[1];var opt=document.createElement("option");citySelect.options.add(opt);opt.value=cvalue;opt.innerHTML=cname;}}}
說明:
document.all("pro").value,根據name或id取值,這裡用來擷取select選項的value值;
把選擇的option的value通過ajax提交到後台,先不看回呼函數;
後台java程式:
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 Pcs extends HttpServlet {protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.equals("utf-8");response.setCharacterEncoding("utf-8");String pro=request.getParameter("pro");String cities="";if(pro.equalsIgnoreCase("beijing")){cities="haidian,海澱|changping,昌平|chaoyang,朝陽";}else if(pro.equalsIgnoreCase("shandong")){cities="jinan,濟南|dezhou,德州|qingdao,青島";}else if(pro.equalsIgnoreCase("hebei")){cities="shijiazhuang,石家莊|langfang,廊坊|xingtai,邢台";}else{cities=",--請選擇--";}PrintWriter out=response.getWriter();out.print(cities);out.flush();out.close();}}
說明:
正常的市是根據省在資料庫查詢出來的,為了方便我直接寫在了字串中;
在回呼函數中我返回的是有一定格式的字串,再在回呼函數裡用split分割;
注意最後一個else不能省掉,不然會在市裡可能出現undefinded;
關於回呼函數的說明:
var citySelect=document.all("cit");拿到市的select對象;
citySelect.options得到所有option對象,從後向前迴圈刪掉option(因為這是我前一個選擇出來的市,換了省市就得換);
var city=result.split("|");擷取所有市(option的value,option的文本子節點),進行遍曆;
var vn=city[i].split(",");
var cvalue=vn[0];
var cname=vn[1]; 擷取option的value和文本節點
建立元素節點 option,並為select加子節點;
給option加value和文本節點;