利用JSON模拟数据,ajax获取并返回,显示在网页
JSON:
{
"air":[
{
"id":1,
"city":"杭州",
"airport":"杭州机场"
},
{
"id":2,
"city":"上海",
"airport":"浦东机场"
},
{
"id":3,
"city":"北京",
"airport":"首都机场"
},
{
"id":4,
"city":"成都",
"airport":"成都机场"
},
{
"id":5,
"city":"南京",
"airport":"南京机场"
},
{
"id":6,
"city":"天津",
"airport":"天津机场"
}
]
}
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>json模拟数据</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.container {
width: 800px;
margin: 200px auto;
padding: 30px 0;
border: 1px dashed #272627;
}
.test {
width: 100%;
padding: 10px 0;
margin: 20px 0;
color: #4bade8;
font-size: 18px;
text-align: center;
}
#jsonList {
width: 500px;
margin: 0 auto;
}
#jsonTable th,
td {
padding: 6px 0;
line-height: 30px;
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<div class="test">城市信息数据</div>
<table border="1" cellspacing="0" bordercolor="#4bade8" cellpadding="0" id="jsonList">
<tr>
<th>编号</th>
<th>城市</th>
<th>机场</th>
</tr>
</table>
</div>
<script src="js/jquery-1.12.3.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(function() {
getAir();
function getAir() {
var temp = '';
$.ajax({
type: "get",
url: "AirportList.json",
dataType: "json",
success: function(res) {
var list = res.air;
console.log(list);
for(var $i = 0; $i < list.length; $i++) {
temp +=
'<tr>' +
'<td>' + list[$i].id + '</td>' +
'<td>' + list[$i].city + '</td>' +
'<td>' + list[$i].airport + '</td>' +
'</tr>';
}
$("#jsonList tr:not(:first)").html("");
$("#jsonList").append(temp);
}
});
}
});
</script>
</body>
</html>
模拟效果: