您的位置:首页 > Web前端 > HTML

Ajax在html页面获取后台XML文件资源

2015-09-27 09:06 567 查看
一、准备工具

站长吧ASP调试工具.exe,这个工具是为了快速建立asp环境,方便调试。



二、建立文件夹

1.建立网站根文件夹,名字随意,将站长吧ASP调试工具.exe复制到根文件夹;

2.建立xml子文件夹,在其中建立book.xml文件。

<?xml version="1.0" encoding="iso-8859-1"?>
<!--  Copyright w3school.com.cn -->
<!-- W3School.com.cn bookstore example -->
<bookstore>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="web" cover="paperback">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
</bookstore>


3.在根文件夹建立index.html页面。

<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
//是按钮单击调用的函数
function loadXMLDoc(){
var xmlhttp;//XHR对象
var txt,x,i;

//根据不同版本浏览器获得XHR对象
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

//XHR状态改变函数,这也是前端使用XHR的主要函数
xmlhttp.onreadystatechange=function(){
//下面的条件几乎是固定写法
if (xmlhttp.readyState==4 && xmlhttp.status==200){
//获取从服务器上发回来的数据,为XML类型
xmlDoc=xmlhttp.responseXML;
txt="";
//把标签为"title"的文本对象提取出来,放到数组x中
x=xmlDoc.getElementsByTagName("title");
//逐一读取数组,取得每一个元素第一个节点的值,即图书名称,追加给文本字符串
for (i=0;i<x.length;i++){
txt=txt + x[i].childNodes[0].nodeValue + "<br />";
}
//在文本中更新
document.getElementById("myDiv").innerHTML=txt;
}
}
//执行发送任务
xmlhttp.open("GET","xml/books.xml",true);
xmlhttp.send();
}
</script>
</head>

<body>

<h2>My Book Collection:</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">获得我的图书收藏列表</button>

</body>
</html>


三、执行效果

1.运行站长吧ASP调试工具.exe,默认浏览器会自动弹出主页,也可以在浏览器中输入电脑的IP来访问;



2.单击按钮,页面局部刷新。



四、小结:

1.本例中读取的是一个xml文件,所以用了xmlDoc=xmlhttp.responseXML,如果是文本文件或者字符串,就要用到xmlhttp.responseText;

2.具体资料参考http://www.w3school.com.cn/ajax/ajax_xmlhttprequest_response.asp。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: