您的位置:首页 > 理论基础 > 计算机网络

XMLHttpRequest学习笔记一

2011-10-07 13:22 351 查看
通过XMLHttpRequest从服务端获取数据,并以表格方式进行展现,代码如下:

<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

response.setHeader("Pragma","No-Cache");
response.setHeader("Cache-Control","No-Cache");
response.setHeader("Expires","0");
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'testxmlhttprequest.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

</head>

<body>
<!-- 请求服务器端的xml数据文件,并以表格方式进行展现 -->
<script type="text/javascript">

var xmlHttpRequest;
function createXMLHttpRequest() {
//support IE7+,firefox,Chrome,Opera,Safari and so on
if (window.XMLHttpRequest) {
xmlHttpRequest = new XMLHttpRequest();
} else {
//support IE6,IE5
//xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
xmlHttpRequest = new ActiveXObject("MSXML2.XMLHTTP.3.0");
}
return xmlHttpRequest;
}

//创建xmlhttp请求对象
xmlHttpRequest = createXMLHttpRequest();
xmlHttpRequest.open("GET","webpage/book.xml",false);
xmlHttpRequest.send();

//
alert(xmlHttpRequest.responseText);

var xmldom = xmlHttpRequest.responseXML;
//解析XMLDOM
var e_books = xmldom.getElementsByTagName("books")[0];
var e_book_array = e_books.childNodes;
document.writeln("<table border='1'>");
document.writeln("<tr><th>ID</th><th>Name</th><th>Author</th></tr>");
for(var i=0; i<e_book_array.length; i++) {
var e = e_book_array[i];
document.writeln("<tr><td>" + e.getElementsByTagName("id")[0].childNodes[0].nodeValue
+ "</td><td>" + e.getElementsByTagName("name")[0].childNodes[0].nodeValue
+ "</td><td>" + e.getElementsByTagName("author")[0].childNodes[0].nodeValue
+ "</td></tr>");
}
document.writeln("</table>");

</script>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: