标签:
1, xml 文件
<?xml version="1.0" encoding="utf-8"?>
<root>
<person>
<name type="star">王力宏</name>
<photo>./images/wlh.jpg</photo>
<album><<改变自已>></album>
<age>39</age>
<sex>男</sex>
</person>
<person>
<name type="star">周杰伦</name>
<photo>./images/wlh.jpg</photo>
<album><<我很忙>></album>
<age>39</age>
<sex>男</sex>
</person>
<person>
<name type="star">王力宏</name>
<photo>./images/wlh.jpg</photo>
<album><<改变自已>></album>
<age>39</age>
<sex>男</sex>
</person>
<person>
<name type="star">王力宏</name>
<photo>./images/wlh.jpg</photo>
<album><<改变自已>></album>
<age>39</age>
<sex>男</sex>
</person>
<person>
<name type="star">王力宏</name>
<photo>./images/wlh.jpg</photo>
<album><<改变自已>></album>
<age>39</age>
<sex>男</sex>
</person>
<person>
<name type="star">王力宏</name>
<photo>./images/wlh.jpg</photo>
<album><<改变自已>></album>
<age>39</age>
<sex>男</sex>
</person>
</root>
2,
<?php
// 理论上数据是从数据库取出
// 由PHP处理程序,生成一个xml文档
// 为了学习目的,我们简化了步聚,手工创建了一个xml
header(‘Content-Type: text/xml; charset=utf-8‘);
// 获取xml文档
$result = file_get_contents(‘./stars.xml‘);
// 将xml文档返回
echo $result;
?>
3, 显示到页面
<script>
var btn = document.querySelector(‘[type=button]‘);
btn.onclick = function () {
var xhr = new XMLHttpRequest;
xhr.open(‘get‘, ‘stars.php‘);
xhr.send(null);
xhr.onreadystatechange = function () {
if(xhr.readyState == 4 && xhr.status == 200) {
// var result = xhr.responseText;
// 当返回的内容为xml格式时
var result = xhr.responseXML;
console.log(result);
// 通过DOM解析
var persons = result.getElementsByTagName(‘person‘);
// console.log(persons.length);
var html = ‘‘;
// 遍历生成HTML字符串
for(var i=0; i<persons.length; i++) {
var name = persons[i].getElementsByTagName(‘name‘)[0];
var sex = persons[i].getElementsByTagName(‘sex‘)[0];
var age = persons[i].getElementsByTagName(‘age‘)[0];
var photo = persons[i].getElementsByTagName(‘photo‘)[0];
var album = persons[i].getElementsByTagName(‘album‘)[0];
html += ‘<tr>‘;
html += ‘<td>‘ + name.innerHTML + ‘</td>‘;
html += ‘<td>‘ + sex.innerHTML + ‘</td>‘;
html += ‘<td>‘ + age.innerHTML + ‘</td>‘;
html += ‘<td>‘ + photo.innerHTML + ‘</td>‘;
html += ‘<td>‘ + album.innerHTML + ‘</td>‘;
html += ‘</tr>‘;
}
//console.log(html);
// 将拼凑好的字符串,添加到DOM中
document.querySelector(‘table‘).innerHTML = html;
}
}
}
</script>
标签:
原文地址:http://www.cnblogs.com/angyangzhanfang/p/5820158.html