jQuery 解析xml文件

来源:互联网 发布:linux设定文件夹权限 编辑:程序博客网 时间:2024/06/17 19:51
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>jquery xml解析</title> <script src="jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function(){ $.ajax({url:"City.xml", success:function(xml){ $(xml).find("province").each(function(){ var t = $(this).attr("name");//this-> $("#DropProvince").append("<option>"+t+"</option>"); }); } }); $("#DropProvince").change(function(){ $("#sCity>option").remove(); var pname = $("#DropProvince").val(); $.ajax({url:"City.xml", success:function(xml){ $(xml).find("province[name='"+pname+"']>city").each(function(){ $("#sCity").append("<option>"+$(this).text()+"</option>"); }); } }); }); }); </script> </head> <body> <form id="form1"> <div> <select id="DropProvince" style="width:60px;"> <option>请选择</option> </select> <select id="sCity" style="width:60px;"> </select> </div> </form> </body> </html> 

city.xml文件

<?xml version="1.0" encoding="utf-8" ?> <provinces> <province name="湖北"> <city>武汉</city> <city>黄石</city> <city>宜昌</city> <city>天门</city> </province> <province name="湖南"> <city>邵阳</city> <city>长沙</city> <city>岳阳</city> </province> <province name="广东"> <city>广州</city> <city>深圳</city> </province> </provinces>

其实主要是注意怎样在html界面上解析xml文件,格式就是

<script type="text/javascript"> $(document).ready(function () { $.ajax({ url: "City.xml", success: function (xml) { $(xml).find("province").each(function () { var t = $(this).attr("name"); $("#DropProvince").append("<option>" + t + "</option>"); }); } }); $("#DropProvince").change(function () { $("#sCity>option").remove(); var pname = $("#DropProvince").val(); $.ajax({ url: "City.xml", success: function (xml) { $(xml).find("province[name='"+pname+"']>city").each(function(){ $("#sCity").append("<option>"+$(this).text()+"</option>"); }); } }); }); }); </script> 

就是用.ajax()xml.each()进行循环操作,基本思想就是这样的,成功之后去执行success这个回调函数。这里的xml文件是用来存储数据的,相当于在数据库中读取文件。

0 0