下面主要介绍client的代码:
1
//先假设server传过来如下的xml文件内容:
2
<?
xml version="1.0" encoding="gb2312"
?>
3
<
students
>
4
<
student
name
="木鱼子"
>
5
<
job
>
Programmer
</
job
>
6
<
salary
>
3000
</
salary
>
7
</
student
>
8
<
student
name
="丁磊"
>
9
<
job
>
网易CEO
</
job
>
10
<
salary
>
100000
</
salary
>
11
</
student
>
12
<
student
name
="陈天桥"
>
13
<
job
>
盛大CEO
</
job
>
14
<
salary
>
120000
</
salary
>
15
</
student
>
16
</
students
>
1
//类的构造,传入xml文档和需要处理的标签名称
2
function DataSet(xmldoc, tagLabel) {
3
this.rootObj = xmldoc.getElementsByTagName(tagLabel)
4
5
//3个方法定向,方便调用
6
this.getCount = getCount
7
this.getData = getData
8
this.getAttribute = getAttribute
9
}
1
//3个方法函数定义
2
function getCount(){
3
return this.rootObj.length
4
}
5
6
function getData(index, tagName){
7
if (index >= this.count){
8
return "index overflow"
9
}
10
var node = this.rootObj[index]
11
var str = node.getElementsByTagName(tagName)[0].firstChild.data
12
return str
13
}
14
15
function getAttribute(index, tagName) {
16
if (index >= this.count){
17
return "index overflow"
18
}
19
var node = this.rootObj[index]
20
var str = node.getAttribute(tagName)
21
return str
22
}
//使用DataSet类获取所需标签集合
1
function updateByXML(xmlDoc) {
2
var studentDS = new DataSet(xmlDoc,"student");
3
var count = studentDS.getCount()
4
for(i=0;i
<
count
;i++) {
5
var name
= studentDS.getAttribute(i,"name")
6
var job
= studentDS.getData(i,"job")
7
var salary
= studentDS.getData(i,"salary")
8
alert(name + "," + job + "," + salary)
9
}
10
}
//操纵DOM,创建table,显示获得的数据,用这种方法显示数据,容易让用户接受!~^_^
1
//
首先要确定document对象中,有没有定义table
2
function
deleteOldTable()
{
3
delRow
=
document.getElementsByTagName(
"
table
"
).length
4
5
if
(delRow
==
0
)
{
6
return
;
7
}
8
9
var
node
=
document.getElementsByTagName(
"
table
"
)[delRow
-
1
];
//
表格
10
var
c
=
node.childNodes.length
11
12
for
(i
=
0
;i
<
c;i
++
)
{
13
node.removeChild(node.childNodes[
0
]);
//
删除全部单元行
14
}
15
16
}
1
//
传入DataSet的一个实例即可
2
function
makeTable(m_ds)
{
3
deleteOldTable()
//
先清除以前的结果
4
5
var
table
=
document.createElement(
"
table
"
);
6
table.setAttribute(
"
border
"
,
"
1
"
);
7
table.setAttribute(
"
width
"
,
"
100%
"
);
8
9
document.body.appendChild(table);
10
var
header
=
table.createTHead();
11
var
headerrow
=
header.insertRow(
0
);
12
headerrow.insertCell(
0
).appendChild(document.createTextNode(
"
姓名
"
));
13
headerrow.insertCell(
1
).appendChild(document.createTextNode(
"
职业
"
));
14
headerrow.insertCell(
2
).appendChild(document.createTextNode(
"
工资
"
));
15
16
for
(
var
i
=
0
;i
<
m_ds.getCount();i
++
)
{
17
var
name
=
m_ds.getAttribute(i,
"
name
"
)
18
var
job
=
m_ds.getData(i,
"
job
"
)
19
var
salary
=
m_ds.getData(i,
"
salary
"
)
20
var
row
=
table.insertRow(i
+
1
);
21
row.insertCell(
0
).appendChild(document.createTextNode(name));
22
row.insertCell(
1
).appendChild(document.createTextNode(job));
23
row.insertCell(
2
).appendChild(document.createTextNode(salary));
24
}
25
}
以上就是javascript的DOM的基本使用方法,作为ajax的基础,掌握这个是非常重要滴!~