1. 程式人生 > >JQuery實現AJAX異步請求實現省市聯動(數據傳輸格式為xml)

JQuery實現AJAX異步請求實現省市聯動(數據傳輸格式為xml)

集合 .html 省市聯動 utf func app 字符串 tco name

AJAX的響應的數據格式:

  文本,一段HTML的數據,XML,JSON。

使用工具生成xml的文件:

  通常使用XStream工具,將集合,數組,對象轉化成XML格式。

    步驟一:導入XStream工具包:xpp3_min-1.1.4c.jar;xstream-1.4.4.jar;

    步驟二:XStream的使用:

            List<City> list = ps.searchCityByPid(pid);
            XStream xStream =  new XStream();//創建XStream對象
            xStream.alias("city", City.class
);//設置將對象的全路徑替換為你指定的字符串 //如果不做下面的設置,那麽轉換為xml後,對象和對象成員變量的關系如同xml中父標簽和子標簽的關系; //如下設置為轉換為xml後,對象和對象成員變量的關系如果xml中一個標簽中有多個屬性的關系; //xStream.useAttributeFor(City.class, "cname");//設置對象目標成員變量轉換後為xml中標簽屬性。 //xStream.useAttributeFor(City.class, "cid"); String xmlStr = xStream.toXML(list);
//這裏設置為text/xml;那麽前端頁面回響的數據類型就為[object XMLDocument] //倘若這裏設置為text/html,那麽前端就是html標簽即字符串 response.setContentType("text/xml;charset=utf-8"); response.getWriter().print(xmlStr);

在客戶端解析xml文件:

 1 <html>
 2 <head>
 3 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"
> 4 <title>Hello Miss Dang</title> 5 </head> 6 <script src="${pageContext.request.contextPath}/js/jquery-1.11.3.min.js"></script> 7 <script type="text/javascript"> 8 $(function(){ 9 $("#province").change(function(){ 10 var pid = $(this).val(); 11 $.post("${pageContext.request.contextPath}/CitysServlet",{"pid":pid},function(data){ 12 alert(data); 13 $("#city").html("<option>-請選擇市-</option>"); 14 $(data).find("city").each(function(){ 15 var cid = $(this).children("cid").text(); 16 var cname = $(this).children("cname").text(); 17 $("#city").append("<option value = ‘"+cid+"‘>"+cname+"</option>"); 18 }); 19 }); 20 }); 21 }); 22 23 </script> 24 <body> 25 <form> 26 <select id="province"> 27 <option>-請選擇省-</option> 28 <c:forEach var="i" items="${ list }"> 29 <option value="${ i.pid }">${ i.pname }</option> 30 </c:forEach> 31 </select> 32 <select id = "city"> 33 34 </select> 35 </form> 36 </body> 37 </html>

    

JQuery實現AJAX異步請求實現省市聯動(數據傳輸格式為xml)