前端代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>通过AJAX获取数据列表</title>
<style>
* {
margin: 0;
padding: 0;
}
ul {
list-style: none;
}
h3 {
padding: 0;
text-align: center;
border-bottom: 1px solid #ccc;
}
#list li {
padding: 6px 4px;
border-bottom: 1px solid #ccc;
}
#list li a {
float: right;
text-decoration: none;
color: red;
font-weight: 700;
}
</style>
<script>
window.onload = function () {
//给A链接添加删除事件
var
oList = document.getElementById('list'),
aA = oList.getElementsByTagName('a');
//添加删除功能
oList.onclick = function (ev) {
var
ev = ev || window.event,
oTarget = ev.srcElement || ev.target;
if(oTarget.tagName === 'A'){
oList.removeChild(oTarget.parentNode);
}
}
//通过AJAX获取实时数据
if(window.ActiveXObject){
var oXr = new window.ActiveXObject('Microsoft.XMLHTTP');
}else {
var oXhr = new XMLHttpRequest();
}
oXhr.open('GET','http://localhost/ajax/ajax1.php');
oXhr.send();
oXhr.onreadystatechange = function () {
if(oXhr.readyState === 4 && oXhr.status === 200){
var oData = JSON.parse(oXhr.responseText);
for(var i = 0; i < oData.length; i++){
var
oLi = document.createElement('li');
oLi.innerHTML = '<a href="javascript:;">×</a>' + oData[i].name;
oList.appendChild(oLi);
}
console.log(JSON.parse(oXhr.responseText));
}
}
}
</script>
</head>
<body>
<h3>明星列表</h3>
<ul id="list"></ul>
</body>
</html>
后端代码:
<?php
header("Access-Control-Allow-Origin:*");
$json = array(
array(
'id'=>1,
'name'=>'刘德华',
'age'=>56,
),
array(
'id'=>2,
'name'=>'张学友',
'age'=>56,
),
array(
'id'=>3,
'name'=>'郭富城',
'age'=>56,
),
array(
'id'=>4,
'name'=>'梁家辉',
'age'=>56,
)
);
echo json_encode($json);
?>