上回介绍了使用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>
下载点这里