(特感谢李南江老师提供视频教学)
html结构:
<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>
js:
<script> window.onload = function (ev) { // 1.获取需要设置的元素 var oTitle = document.querySelector("#title"); var oDes = document.querySelector("#des"); var oImg = document.querySelector("img"); // 2.获取所有按钮 var oBtns = document.querySelectorAll("button"); // 3.给按钮添加点击事件 oBtns[0].onclick = function () { var self = this; // 4.发送Aajx请求到服务器 ajax({ type:"get", url:"10-ajax-test.php", data:{"name":this.getAttribute("name")}, timeout: 3000, success: function (xhr) { console.log(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) { alert(xhr.status); } }); } oBtns[1].onclick = function () { } oBtns[2].onclick = function () { } } </script>
php代码获取格式:
<?php
//获取xml格式需添加这条 header("content-type:text/xml; charset=utf-8"); echo file_get_contents("10-ajax-test.xml");
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/2.jpg</image> </bb> <tx> <title>键盘拖鞋</title> <des>程序员专属拖鞋, 屌丝气息浓郁, 你值得拥有</des> <image>images/3.jpg</image> </tx> </products>