例1: ===================================================== XML內容為: <?xml version="1.0" encoding="utf-8" ?> <stulist> <man> <name>zdz</name> <age>25</age> </man> <man> <name>liufeng</name> <age>22</age> </man> <man> <name>hotman</name> <age>18</age> </man> </stulist> ===================================== <script> $(document).ready(function(){ $.ajax({url:"test.xml",dataType:"xml",success:function(xml){ $(xml).find("stulist>man").each(function(){ document.getElementById("zdzDiv").innerHTML += "<br>姓名:"+$(this).find("name").text()+"<br/>年齡:"+$(this).find("age").text(); }); }}); }) </script> <div id="zdzDiv"> ===================================== 參數1 url:要請求的文檔路徑. 參數2 dataType:請求的文件類型.有 XML HTML script json等等. 參數3 success:請求成功後的回呼函數。 $(xml).find("stulist>man").each尋找返回的xml裡的stulist節點下的man標籤.並根據尋找到的結果執行裡面的函數. 在man標籤下繼續尋找子項目,並將值放到顯示的div裡面. ========================================================================================== 例2: function Resultxml() { $.ajax ({ url: 'ajaxRespose.aspx', data: {id: 1, name: $('#gender').val()}, dataType: 'xml', success: function(xml) { alert(xml); $(xml).find('select').each(function() { var option1 = "<OPTION value='"; var option2 = "'>"; var option3 = "</OPTION>"; var text = $(this).children("text").text(); var value = $(this).children("value").text(); $("#city").append(option1 + value + option2 + text + option3); }); } }); } 服務端返回的xml檔案 String targetId = Request.QueryString["id"]; // 獲得請求中參數為id的值 String xml_version = "<?xml version=/"1.0/" encoding=/"UTF-8/"?>"; String xml_start = "<selects>"; String xml_end = "</selects>"; String xml = ""; switch (targetId) { case "0": xml = "<select><value>0</value><text>請選擇</text></select>"; break; case "1": xml = "<select><value>1</value><text>昌平</text></select>"; xml += "<select><value>2</value><text>丰台</text></select>"; break; case "2": xml = "<select><value>1</value><text>塘沽區</text></select>"; xml += "<select><value>2</value><text>漢沽區</text></select>"; break; } String last_xml = xml_version+xml_start + xml + xml_end; Response.ContentType = "text/xml";//返回資料類型為xml(必須的) Response.Write(last_xml); Response.End(); |