1. 程式人生 > >jquery如何通過ajax請求獲取後臺資料顯示在表格上

jquery如何通過ajax請求獲取後臺資料顯示在表格上

1.引入bootstrap和jquery的cdn

<link rel="stylesheet" type="text/css" href="https://cdn.bootcss.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
<script type="text/javascript" src="https://cdn.bootcss.com/jquery/1.4.0/jquery.js"></script>
2.html部分
<table class="table table-bordered" id='tabletest'
> <tr> <th>名字</th> <th>開始時間</th> <th>是否真實</th> <th>裝置</th> </tr> </table>
3.js部分

1>使用for in

$(function(){
    $.ajax({
        url:'data.json',
type:'get',
dataType:'json',
success:function(data){
            //方法中傳入的引數data為後臺獲取的資料
for(i in data.data) //data.data指的是陣列,數組裡是8個物件,i為陣列的索引 { var tr; tr='<td>'+data.data[i].name+'</td>'+'<td>'+data.data[i].startTime+'</td>'+'<td>'+data.data[i].is_true+'</td>'+'<td>'+data.data[i].device+'</td>' $("#tabletest").append('<tr>'
+tr+'</tr>') } } }) })
     ***注意**** for in 通常用於物件

     遍歷陣列的兩種方法(each,foreach)

     $.each(arr,function(index,item){})

     arr.forEach(function(item,index))

    //  arr為陣列 ,index索引,item為當前值

 2>each方法

        $(function(){
             $.ajax({
            url:'data.json',
type:'get',
dataType:'json',
success:function(data){
                $.each(data.data,function(index,item){
                    var tr;
tr='<td>'+item.name+'</td>'+'<td>'+item.startTime+'</td>'+'<td>'+item.is_true+'</td>'+'<td>'+item.device+'</td>';
$("#tabletest").append('<tr>'+tr+'</tr>')
                })
            }
})})
總結獲取物件屬性的方法:item.name或item['name']

jquery新增節點方法:

          ul.append('<li>'+哈哈+'</li>')  

          append:在</ul>之前新增li

          prepend:在<ul>之後新增li

          before:在<ul>之前新增li

          after:在</ul>之後新增li

-----延伸----

(1)將資料中is_true中的0轉換為中文

    採用三目運算或條件判斷

item.is_true=parseInt(item.is_true)==0?'否':'是'
//注意資料是string型別需轉換,且三目運算子返回的是結果不能寫成item.is_true==0? item.is_true='否': item.is_true='是'
(2)將資料中device過濾只顯示冒號以前的資料
item.is_true=parseInt(item.is_true)==0?'否':'是'
var arr=item.device.split(":")
item.device=arr[0]
split()分隔符方法用於把一個字串分割成字串陣列

4.data.json檔案

{
  "status": 0,
"data": [  
        {  
           
            "name": "天王蓋地虎",  
"startTime": "2017-03-02 00:00",
"is_true":"0",
"device": "SM-C9000:samsung"
},  
{  
             
            "name": "寶塔鎮河妖",  
"startTime": "2017-03-02 00:00"  ,
"is_true":"0",
"device": "SM705:smartisan"
},  
{  
             
            "name": "鋤禾日當午",  
"startTime": "2017-03-02 00:00" ,
"is_true":"0" ,
"device": "EVA-AL00:HUAWEI"
}
    ]
}

效果圖