一:a.php
<?php
header("content-type:text/xml;charset=utf-8");
echo file_get_contents("info.xml");
二:b.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{
margin: 0;
padding: 0;
}
div{
width: 300px;
height: 300px;
border: 1px solid #000;
margin: 50px auto;
text-align: center;
background: #ccc;
}
img{
width: 200px;
height: 200px;
display: block;
margin: 10px auto 10px;
border: 1px solid #000;
}
p{
text-align: center;
background: pink;
}
</style>
<script src="d.js"></script>
<script>
window.onload=function(ev){
var oTitle = document.querySelector("#title");
var oDes = document.querySelector("#des");
var oImg = document.querySelector("img");
var oBtns = document.querySelectorAll("button");
oBtns[0].onclick=function(){
var self=this;
Ajax({
type:"get",
url:"a.php",
data:{"name":this.getAttribute("name")},
timeout: 3000,
success:function(xhr){
var name=self.getAttribute("name");
var res=xhr.responseXML;
var title=res.querySelector(name+">title").innerHTML;
var des=res.querySelector(name+">des").innerHTML;
var image=res.querySelector(name+">image").innerHTML;
oTitle.innerHTML=title;
oDes.innerHTML=des;
oImg.setAttribute("src",image);
},
error:function(xhr){
console.log(xhr.status);
}
})
}
}
</script>
</head>
<body>
<div>
<p id="title">商品标题名称</p>
<img src="" alt="">
<p id="des">商品描述信息</p>
<button name="nz">女装</button>
<button name="bb">包包</button>
<button name="tx">拖鞋</button>
</div>
</body>
</html>
三:d.js
function obj2str(data) {
data = data || {};
data.t = new Date().getTime();
var res = [];
for(var key in data){
res.push(encodeURIComponent(key)+"="+encodeURIComponent(data[key]));
}
return res.join("&");
}
function Ajax(option) {
var str = obj2str(option.data);
var xmlhttp, timer;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if(option.type.toLowerCase() === "get"){
xmlhttp.open(option.type, option.url+"?"+str, true);
xmlhttp.send();
}else{
xmlhttp.open(option.type, option.url,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(str);
}
xmlhttp.onreadystatechange = function (ev2) {
if(xmlhttp.readyState === 4){
clearInterval(timer);
if(xmlhttp.status >= 200 && xmlhttp.status < 300 ||
xmlhttp.status === 304){
option.success(xmlhttp);
}else{
option.error(xmlhttp);
}
}
}
if(option.timeout){
timer = setInterval(function () {
console.log("中断请求");
xmlhttp.abort();
clearInterval(timer);
}, option.timeout);
}
}
四:info.xml
<?xml version="1.0" encoding="UTF-8" ?>
<products>
<nz>
<title>甜美女装</title>
<des>甜美系列</des>
<image>images/1.jpg</image>
</nz>
<bb>
<title>奢华女包</title>
<des>送女友</des>
<image>images/1=2.jpg</image>
</bb>
<tx>
<title>键盘拖鞋</title>
<des>程序员专属拖鞋</des>
<image>images/3.jpg</image>
</tx>
</products>