最近写ipad客户端,需要用到jquery,所以学习一下,用到了jquery如何解析xml文件,和大家分享一下。
1、首先建立一个City.xml文件
View Code
1 <?xml version="1.0" encoding="utf-8" ?> 2 <provinces> 3 <province name="湖北"> 4 <city>武汉</city> 5 <city>黄石</city> 6 <city>宜昌</city> 7 <city>天门</city> 8 </province> 9 <province name="湖南"> 10 <city>邵阳</city> 11 <city>长沙</city> 12 <city>岳阳</city> 13 </province> 14 <province name="广东"> 15 <city>广州</city> 16 <city>深圳</city> 17 </province> 18 </provinces>
2、在web前端建立一个Province.htm的界面
View Code
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <title>省市选择</title> 5 <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script> 6 <script type="text/javascript"> 7 $(document).ready(function () { 8 $.ajax({ 9 url: "City.xml", 10 success: function (xml) { 11 $(xml).find("province").each(function () { 12 var t = $(this).attr("name"); 13 $("#DropProvince").append("<option>" + t + "</option>"); 14 }); 15 } 16 }); 17 $("#DropProvince").change(function () { 18 $("#sCity>option").remove(); 19 var pname = $("#DropProvince").val(); 20 $.ajax({ 21 url: "City.xml", 22 success: function (xml) { 23 $(xml).find("province[name='"+pname+"']>city").each(function(){ 24 $("#sCity").append("<option>"+$(this).text()+"</option>"); 25 }); 26 } 27 }); 28 }); 29 }); 30 </script> 31 </head> 32 <body> 33 <form id="form1"> 34 <div> 35 <select id="DropProvince" style=" 60px;"> 36 <option>请选择</option> 37 </select> 38 <select id="sCity" style=" 60px;"> 39 </select> 40 </div> 41 </form> 42 </body> 43 </html>
其实主要是注意怎样在html界面上解析xml文件,格式就是
View Code
1 <script type="text/javascript"> 2 $(document).ready(function () { 3 $.ajax({ 4 url: "City.xml", 5 success: function (xml) { 6 $(xml).find("province").each(function () { 7 var t = $(this).attr("name"); 8 $("#DropProvince").append("<option>" + t + "</option>"); 9 }); 10 } 11 }); 12 $("#DropProvince").change(function () { 13 $("#sCity>option").remove(); 14 var pname = $("#DropProvince").val(); 15 $.ajax({ 16 url: "City.xml", 17 success: function (xml) { 18 $(xml).find("province[name='"+pname+"']>city").each(function(){ 19 $("#sCity").append("<option>"+$(this).text()+"</option>"); 20 }); 21 } 22 }); 23 }); 24 }); 25 </script>
就是用$.ajax()调用xml文件的内容。然后$.each()进行循环操作,基本思想就是这样的,成功之后去执行success这个回调函数。这里的xml文件是用来存储数据的,相当于在数据库中读取文件。