使用jQuery操作XML(转:http://www.pqshow.com/design/Javascript/200909/10223.html)

上回介绍了使用XML DOM操作XML 地址在这     

 

优点:速度快,本地可执行
缺点:需要额外的学习XMLDOM和XPATH相关知识,需要花时间:)

 

这次介绍使用jQuery固有方法操作XML

 

优点:只要会jQuery,不需要额外的XMLDOM,XPATH知识
缺点:速度比DOM慢,只能在服务器运行(必须使用http://xx.com/aa.htm这样的形式访问)
 

XML(data.xml)文件范例

<?xml version="1.0"?>
<root>
<picture>
 <src>images/1.jpg</src>
 <title>名称1</title>
 <content>描述1</content>
</picture>
<picture>
 <src>images/2.jpg</src>
 <title>名称2</title>
 <content>描述2</content>
</picture>
</root>

 

jQuery取第二张图片的URL

 $.ajax({
      url:"data.xml",
      dataType:"xml",
      type:"post",
      success:function(xml){
            alert($(xml).find("src").eq(1).text());
      }
 });

 

当然,直接打开文件是无效,你必须使用http://localhost/xx的形式访问

还是省地市联动例子(速度要比DOM直接处理慢一些)

<select id="sheng"></select>
<select id="shi"></select>
<select id="xian"></select>
<script src="jquery.js"></script>
<script>
$(function(){
    $.ajax({url:"city1.xml",type:"post",dataType:"xml",success:function(msg){
            $(msg).find("Root>Item[pid='0']").each(function(){
                $("<option></option>").text($(this).attr("value")).val($(this).attr("id")).appendTo($("#sheng"));
            });
            $("#sheng").change(function(){
                var id=$(this).val();
                $("#shi").empty();
                $(msg).find("Root>Item[pid='"+id+"']").each(function(){
                    $("<option></option>").text($(this).attr("value")).val($(this).attr("id")).appendTo($("#shi"));
                });
                $("#shi").change();
            });
            $("#shi").change(function(){
                var id=$(this).val();
                $("#xian").empty();
                $(msg).find("Root>Item[pid='"+id+"']").each(function(){
                    $("<option></option>").text($(this).attr("value")).val($(this).attr("id")).appendTo($("#xian"));
                });
            });
            $("#sheng").change();
            $("#shi").change();
        }
    });

});
</script>
 


本文来自: PQ秀秀网(http://www.pqshow.com) 详细出处参考:http://www.pqshow.com/design/Javascript/200909/10223.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值