JQuery實現AJAX非同步請求實現省市聯動(資料轉送格式為xml)

來源:互聯網
上載者:User

標籤:object   hello   格式   back   1.4   ems   page   meta   pen   

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)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.