/******1,Content-Type
很多时候无法解析就是Content-Type的问题。
如果本身就是xml文件,请跳过这一步
动态生成的XML一定要将其设置为text/xml,否则默认就是text/html也就是普通的文本了。
常见语言的Content-Type设置*********/
header(
"Content-Type:text/xml"
);
//php
response.ContentType=
"text/xml"
//asp
response.setHeader(
"ContentType"
,
"text/xml"
);
//jsp
/******
2,xml结构。
XML一定要封闭的,很重要!
例:
错误的XML*********/
<?xml version=
"1.0"
encoding=
"UTF-8"
?>
<name>zhangsan</name>
<id>1</id>
<name>lisi</name>
<id>2</id>
//正确的
<?xml version=
"1.0"
encoding=
"UTF-8"
?>
<stulist>
<student email=
"1@1.com"
>
<name>zhangsan</name>
<id>1</id>
</student>
<student email=
"2@2.com"
>
<name>lisi</name>
<id>2</id>
</student>
</stulist>
/******
3,解析
这里引用macnie的
遍历student(这里还是用上面那个XML,子节点是student)*********/
$.ajax({
url:
'ajax.asp'
,
type:
'GET'
,
dataType:
'xml'
,
//这里可以不写,但千万别写text或者html!!!
timeout: 1000,
error:
function
(xml){
alert(
'Error loading XML document'
+xml);
},
success:
function
(xml){
$(xml).find(
"student"
).each(
function
(i){
var
id=$(
this
).children(
"id"
);
//取对象
var
idvalue=$(
this
).children(
"id"
).text();
//取文本
alert(id_value);
//这里就是ID的值了。
alert($(
this
).attr(
"email"
));
//这里能显示student下的email属性。
//最后么输出了,这个是cssrain的写法,貌似比macnie更JQ一点
$(
'<li></li>'
)
.html(id_value)
.appendTo(
'ol'
);
});
}
});
本文介绍了正确设置Content-Type为text/xml的重要性,并提供了不同编程语言中设置Content-Type的方法。同时,强调了XML文档结构的规范性,包括元素必须闭合等关键点。此外,还展示了使用jQuery进行XML数据解析的具体示例。
4834

被折叠的 条评论
为什么被折叠?



