jQuery+Ajax+js请求json格式数据并渲染到html页面

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>

 

  • 3
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值