JQuery+Axios+JSON实现将JSON中的数据读取出来并显示在前端表格中

JQuery+Axios+JSON实现将JSON中的数据读取出来并显示在前端表格中

1.任务需求
页面中给出学生姓名、年龄、手机号、家庭住址等表头,信息项为空,点击“加载数据”按钮,触发加载数据函数,通过axios异步请求json文件中的数据,并显示在页面上,按钮点击完后设置为失效状态,即不允许重复加载数据。
2.首先准备"student.json"文件,自定义若干数据,格式如下

[{"userName":"","age":,"phoneNum":" ","address":""},
 {"userName":"","age":,"phoneNum":" ","address":""},
   .........
]

3.代码如下

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>用户信息</title>
  <link href="/bootstrap/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
  <div class="container">
    <div class="row">
      <table style="width: 600px;height: 200px;" id="tableid" class="table table-bordered">
        <thead>
          <tr>
            <td>用户名</td>
            <td>年龄</td>
            <td>手机号</td>
            <td>地址</td>
          </tr>
        </thead>
     </table>
     <button id="bt" onclick="getLoad();">加载数据</button>
    </div>
  </div>
</body>
<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
<script src="/bootstrap/js/bootstrap.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
 //axios异步加载数据
 function getLoad(){
 //这里的json文件地址是自己的
  axios.get('/json/student.json',{}).then(function(response){
     var attr=response.data;
    $.each(attr,function(index,value){
     //在页面显示数据
     $("#tableid").append("<tr><td>" +attr[index].userName+"</td>"+
                               "<td>" + attr[index].age+"</td>"+
                               "<td>"+attr[index].phoneNum+"</td>"+
                               "<td>"+attr[index].address+"</td></tr>");
    })
    });
    $("#bt").attr("disabled", true);//按钮设置为失效
 }
</script>
</html>

注:代码中BootStrap我的引入的是本地目录下的,当然也可以使用网络引入。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值