1、先给json格式的数据:
[
{"id":1,"name":"stan"},
{"id":2,"name":"jack"},
{"id":3,"name":"lucy"},
{"id":4,"name":"mary"},
{"id":5,"name":"jerry"},
{"id":6,"name":"tom"}
]
2、通过访问html页面,获取并展示数据:
方法一:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<body>
<div id="test">
</div>
<script type="text/javascript">
window.onload=function(){
//js代码请求
}
$(function(){
$.ajax({
method:"post",
url:"http://localhost:81/getpersons",/*这里要写nginx访问的全路径*/
data:{},
dataType: "json",
success: function(data){
var str="<ul>";
$.each(data,function(i,items){
str+="<li>"+"ID:"+items.id+"</li>";
str+="<li>"+"姓名:"+items.name+"</li>";
});
str+="</ul>";
$("div").append(str);
}
});
})
</script>
</body>
</html>
方法二:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<body>
<div id="test">
<table border="1" cellspacing="1" cellpadding="1" id="a1">
</table>
</div>
<script type="text/javascript">
window.onload=function(){
//js代码请求
}
$(function(){
$.ajax({
method:"post",
url:"http://localhost:81/getpersons",/*这里要写nginx访问的全路径*/
data:{},
success: function(data){
alert(data);
//将json数据转换
dd=eval("("+data+")");
var htmls;
for(var i=0;i<dd.length;i++){
htmls="<tr>+<td>"+"id: "+dd[i].id+"</td>+<td>"+"name :"+dd[i].name+"</td>+</tr>";
$("#a1").append(htmls);
}
}
});
})
</script>
</body>
</html>