1,Content-Type
很多时候无法解析就是Content-Type的问题。
如果本身就是xml文件,请跳过这一步
动态生成的XML一定要将其设置为text/xml,否则默认就是text/html也就是普通的文本了。
常见语言的Content-Type设置
1 header("Content-Type:text/xml"); //php
2 response.ContentType="text/xml" //asp
3 response.setHeader("ContentType","text/xml"); //jsp
XML一定要封闭的,很重要!
例:
错误的XML
1 <?xml version="1.0" encoding="UTF-8"?>
2 <name>zhangsan</name>
3 <id>1</id>
4 <name>lisi</name>
5 <id>2</id>
6
正确的

Code
1 <?xml version="1.0" encoding="UTF-8"?>
2 <stulist>
3 <student email="1@1.com">
4 <name>zhangsan</name>
5 <id>1</id>
6 </student>
7 <student email="2@2.com">
8 <name>lisi</name>
9 <id>2</id>
10 </student>
11 </stulist>
12
3,解析
这里引用macnie的
遍历student(这里还是用上面那个XML,子节点是student)

Code
1
$.ajax(
{
2
url:'ajax.asp',
3
type: 'GET',
4
dataType: 'xml',//这里可以不写,但千万别写text或者html!!!
5
timeout: 1000,
6
error: function(xml)
{
7
alert('Error loading XML document'+xml);
8
},
9
success: function(xml)
{
10
$(xml).find("student").each(function(i)
{
11
var id=$(this).children("id"); //取对象
12
var id_value=$(this).children("id").text(); //取文本
13
alert(id_value);//这里就是ID的值了。
14
alert($(this).attr("email")); //这里能显示student下的email属性。
15
16
//最后么输出了,这个是cssrain的写法,貌似比macnie更JQ一点
17
$('<li></li>')
18
.html(id_value)
19
.appendTo('ol');
20
});
21
}
22
});
23
4,禁用缓存如果你直接使用ajax方法,可以使用cache:false来禁用缓存
注意,是cache:false而不是cache:"false"。布尔值false不是字符串的"false"。
如果你是用get或者post方法,可以在url后面加上时间戳。比如"xml.php?ts"+(+new Date)
注意,不要用随机数,你无法预料到随机数会不会再次随机到……
但是在一切正常的情况下,时间戳是肯定不会重复的。
最后补充一条:保证服务器端是utf-8的编码,否则会乱码!
好啦,完工了,其实也不复杂,对吧?
Tag标签: JavaScript,jQuery,Ajax