您的位置:首页 > 编程语言

Ajax学习笔记(2)----Ajax访问XML实例代码(全)

2008-08-25 21:25 375 查看
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>

<html xmlns=
"http://www.w3.org/1999/xhtml"
>

<head>

<meta http-equiv=
"Content-Type"
content=
"text/html; charset=gb2312"
/>

<title>DOMTest2</title>

<script language=
"javascript"
>

var
request =
false
;

try
{

request =
new
XMLHttpRequest();

}
catch
(trymicrosoft) {

try
{

request =
new
ActiveXObject(
"Msxml2.XMLHTTP"
);

}
catch
(othermicrosoft) {

try
{

request =
new
ActiveXObject(
"Microsoft.XMLHTTP"
);

}
catch
(failed) {

request =
false
;

}

}

}

if
(!request)

alert(
"Error initializing XMLHttpRequest!"
);

function
callServer() {

var
url =
"/Ajax/scripts/saveAddress.xml"
;

request.open(
"POST"
, url,
true
);

request.setRequestHeader(
"Content-Type"
,
"text/xml"
);

request.onreadystatechange = updatePage;

request.send(
null
);

}

function
updatePage() {

if
(request.readyState == 4) {

if
(request.status == 200) {

var
xmlDoc= request.responseXML.documentElement;

var
showElements = xmlDoc.getElementsByTagName(
"show"
);

for
(
var
x=0; x<showElements.length; x++) {

var
title = showElements[x].childNodes[0].text;

var
rating = showElements[x].childNodes[1].text;

document.getElementById(
"title"
).value=title+x;

document.getElementById(
"rating"
).value=rating+x;

}

}

else

if
(request.status == 404)

{ alert(
"Request URL does not exist"
);}

else

if
(request.status == 403) {

alert(
"Access denied."
);

}

else

alert(
"Error: status code is "
+ request.status);

}

}

</script>

</head>

<body>

<table><tr><td>title</td><td><input id=
"title"
type=
"text"
/></td></tr><tr><td>rating</td><td>

<input id=
"rating"
type=
"text"
/></td></tr>

<tr><td></td><td><input type=
"button"
value=
"Click me!"
onclick=
"callServer()"
/></td></tr></table>

</body>

</html>

var


title = showElements[x].childNodes[0].text;

这一句,原写做

var


title = showElements[x].childNodes[0].value;

经过在论坛上讨论得出了正确结果。

XML文件

saveAddress.xml:

<?
xml

version
=
"1.0"

encoding
=
"gb2312"
?>

<
ratings
>

<
show
>

<
title
>
Alias
</
title
>

<
rating
>
6.5
</
rating
>

</
show
>

<
show
>

<
title
>
Lost
</
title
>

<
rating
>
14.2
</
rating
>

</
show
>

<
show
>

<
title
>
Six Degrees
</
title
>

<
rating
>
9.1
</
rating
>

</
show
>

</
ratings
>

得在服务器是运行
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: