1、在Eclipse中创建项目目录视图如下:
2、代码及注解如下
index--02.html
- <!DOCTYPE html>
- <html>
- <head>
- <Meta charset="UTF-8">
- <title>自写AJAX测试--02</title>
- <script type="text/javascript">
- /*****************自己自写程序*************/
- window.onload = function() {
- // 1、获取a节点,并为其添加onclick响应函数
- var test = document.getElementsByTagName('a');
- for(var i = 0; i < test.length; i++) {
- test[i].onclick = function() {
- // 3、创建一个XMLHttpRequest对象
- var request = new XMLHttpRequest();
- // 4、准备发送请求的数据:url、method
- var method = 'GET';
- var url = this.href;
- // 5、调用XMLHttpRequest对象的open方法
- request.open(method,url);
- // 6、调用XMLHttpRequest对象的send方法
- request.send(null);
- // 7、调用XMLHttpRequest对象添加onreadystatechange响应函数
- request.onreadystatechange = function() {
- // 8、判断响应是否完成:XMLHttpRequest对象的readyState属性值为4的时候
- if (request.readyState == 4) {
- // 9、再判断响应是否可用:XMLHttpRequest对象status属性值为200
- if (request.status == 200 || request.status == 304) {
- // 10、打印响应结果:responseText
- document.getElementById('details').innerHTML = request.responseText;
- }
- }
- }
- // 2、取消a节点的默认行为
- return false;
- } // test[i].onclick = function()
- } // for(var i = 0; i < test.length; i++)
- } // window.onload = function()
- </script>
- </head>
- <body>
- <h1>People</h1>
- <ul>
- <li><a href="files/andy.html">Andy</a></li>
- <li><a href="files/richard.html">Richard</a></li>
- <li><a href="files/jeremy.html">Jeremy</a></li>
- </ul>
- <div id="details"></div>
- </body>
- </html>
andy.HTML代码如下所示,jeremy.html、richard.html的代码与andy.HTML代码类似,不同之处在于<body>标签中的<h2>标签中的内容不同。
- <!DOCTYPE html>
- <html>
- <head>
- <Meta charset="UTF-8">
- <title>Insert title here</title>
- </head>
- <body>
- <h2>This is andy.html</h2>
- </body>
- </html>
3、运行结果如下所示: