复制代码 代码如下:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>jquery xml解析</title>
<script src="https://www.jb51.net/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>
<div>
<select>
<option>请选择</option>
</select>
<select>
</select>
</div>
</form>
</body>
</html>
city.xml文件
复制代码 代码如下:
<?xml version="1.0" encoding="utf-8" ?>
<provinces>
<province>
<city>武汉</city>
<city>黄石</city>
<city>宜昌</city>
<city>天门</city>
</province>
<province>
<city>邵阳</city>
<city>长沙</city>
<city>岳阳</city>
</province>
<province>
<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文件是用来存储数据的,相当于在数据库中读取文件。
您可能感兴趣的文章: