<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>04XML解析</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
table {
width: 600px;
border-collapse: collapse;
margin: auto;
}
td {
text-align: center;
}
</style>
</head>
<body>
<table border="1">
<tr>
<th>id编号</th>
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
</tr>
</table>
</body>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
// 页面加载完成之后进行网络请求
// 第一种写法
window.onload = function() {
}
// 获取 table
var table = document.querySelector("table");
// 第二种写法
$(function() {
// get 异步请求
// 1, 创建请求对象
if (window.XMLHttpRequest) {
var xhr = new XMLHttpRequest();
} else{
var xhr = ActiveXObject("Microsoft.XMLHTTP");
}
// 2, 添加监听
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
// 请求成功
// XML 解析
console.log(xhr.responseXML);
xmlJX(xhr.responseXML);
} else{
// 请求失败
console.log("请求失败");
}
}
}
// 3, 启动请求
xhr.open("GET", "./04XML解析.php");
// 4, 发送请求
xhr.send(null);
});
// XML 解析的函数
function xmlJX(XMLdata) {
$(XMLdata).find("student").each(function(i, v) {
// 创建 tr
var tr = $("<tr>").appendTo($("table").eq(0));
$(v).children().each(function(i, v) {
// 创建 td
$("<td>").text($(v).text()).appendTo(tr);
});
});
php代码如下:
<?php //xml特殊点:需要告诉前端,返回的文档类型是 XML格式 header("Content-Type: text/xml;charset=utf-8"); echo " 110 张三 男 10 111 李四 男 110 1110 赵大 女 18 1113 倩儿 女 1110 "; ?>运行如下: