jquery 通過ajax請求獲取后臺數(shù)據(jù)顯示在表格上的方法
1、引入bootstrap和jquery的cdn
<link rel="stylesheet" type="text/css" rel="external nofollow" > <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>設(shè)備</th> </tr> </table>
3、js部分
1>使用for in
$(function(){
$.ajax({
url:'data.json',
type:'get',
dataType:'json',
success:function(data){
//方法中傳入的參數(shù)data為后臺獲取的數(shù)據(jù)
for(i in data.data) //data.data指的是數(shù)組,數(shù)組里是8個對象,i為數(shù)組的索引
{
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 通常用于對象
遍歷數(shù)組的兩種方法(each,foreach):
$.each(arr,function(index,item){})
arr.forEach(function(item,index))
// arr為數(shù)組 ,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>')
})
}
})})
總結(jié):獲取對象屬性的方法:item.name或item['name']
jquery添加節(jié)點方法:
ul.append('<li>'+哈哈+'</li>')
append:在</ul>之前添加li
prepend:在<ul>之后添加li
before:在<ul>之前添加li
after:在</ul>之后添加li
-----延伸----
(1)將數(shù)據(jù)中is_true中的0轉(zhuǎn)換為中文
采用三目運算或條件判斷
item.is_true=parseInt(item.is_true)==0?'否':'是' //注意數(shù)據(jù)是string類型需轉(zhuǎn)換,且三目運算符返回的是結(jié)果不能寫成item.is_true==0? item.is_true='否': item.is_true='是'
(2)將數(shù)據(jù)中device過濾只顯示冒號以前的數(shù)據(jù)
item.is_true=parseInt(item.is_true)==0?'否':'是'
var arr=item.device.split(":")
item.device=arr[0]
split()分隔符方法用于把一個字符串分割成字符串數(shù)組
4.data.json文件
{
"status": 0,
"data": [
{
"name": "天王蓋地虎",
"startTime": "2017-03-02 00:00",
"is_true":"0",
"device": "SM-C9000:samsung"
},
{
"name": "寶塔鎮(zhèn)河妖",
"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"
}
]
}
效果圖:

以上這篇jquery 通過ajax請求獲取后臺數(shù)據(jù)顯示在表格上的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
jQuery實現(xiàn)表單步驟流程導(dǎo)航代碼分享
這篇文章主要介紹了jQuery實現(xiàn)表單步驟流程導(dǎo)航,代碼實現(xiàn)效果簡單精致,推薦給大家,有需要的小伙伴可以參考下。2015-08-08
jQuery實現(xiàn)在HTML文檔加載完畢后自動執(zhí)行某個事件的方法
這篇文章主要介紹了jQuery實現(xiàn)在HTML文檔加載完畢后自動執(zhí)行某個事件的方法,結(jié)合實例形式分析了document的ready()事件自動加載執(zhí)行事件的相關(guān)操作技巧,需要的朋友可以參考下2017-05-05
基于jQuery的一個擴展form序列化到j(luò)son對象
jQuery沒有直接支持form到j(luò)son的序列化方法,目前網(wǎng)上有一個實現(xiàn)是這樣的2010-12-12
jQuery1.3.2 升級到j(luò)Query1.4.4需要修改的地方
jQuery1.3.2 升級到 1.4.4 ,需要修改的地方,需要的朋友可以參考下。2011-01-01

