jquery通過AJAX從后臺獲取信息并顯示在表格上的實現(xiàn)類
在上篇文章給大家介紹了JQuery通過AJAX從后臺獲取信息顯示在表格上并支持行選中 ,現(xiàn)在,抽個時間他們處理了一下,這樣就不需要每次寫代碼了,可以節(jié)省大量的時間,具體請看下文:
具體代碼如下:
//獲取數(shù)據(jù)并顯示數(shù)據(jù)表格
function GetTableData(tableId,ChlickEvent) {
var table = $(tableId);
var url=table.data('url');
$.ajax({
url: url,
type: 'post',
dataType: 'json',
})
.done(function (json) {
var fileds = new Array();
table.children('thead').children('tr').children('th').each(function (index, el) {
var field = $(this).data('field');
fileds[index] = field;
});
var tbody = '';
$.each(json, function (index, el) {
var tr = "<tr>";
$.each(fileds, function (i, el) {
if (fileds[i]) {
tr += '<td>' + formatJsonData(json[index][fileds[i]]) + '</td>';
}
});
tr += "</tr>";
tbody += tr;
});
table.children('tbody').append(tbody);
if (ChlickEvent) {//如果需要支持行選中事件
table.children('tbody').addClass('sel');
table.children('tbody.sel').children('tr').click(function (event) {
$(this).siblings('tr').removeClass('active');//刪除其他行的選中效果
$(this).addClass('active');//增加選中效果
ChlickEvent($(this).children('td:eq(0)').text());//新增點擊事件
});
}
}).fail(function () {
alert("Err");
});
}
//格式化JSON數(shù)據(jù),比如日期
function formatJsonData(jsondata){
if(jsondata==null){
return '無數(shù)據(jù)';
}
else if(/\/Date\(\d+\)/.exec(jsondata)){
var date = new Date(parseInt(jsondata.replace("/Date(", "").replace(")/", ""), 10));
return date.toLocaleString();
}
return jsondata;
}
寫的非常簡單,功能也很少,但是我自己用暫時足夠了。滿足簡單需求。
HTML代碼必須以下格式,必須以POST方式獲取JSON數(shù)據(jù),獲取地址寫到data-url里,數(shù)據(jù)列名寫到data-field里。
支持點擊事件。
用法:
<table id="RoleGroupTable" class="table" data-url="@Url.Action("GetRoleGroups", "Account")">
<thead>
<tr>
<th data-field="ID">ID</th>
<th data-field="Name">名稱</th>
<th data-field="Remark">簡介</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script>
jQuery(document).ready(function ($) {
GetTableData('#RoleGroupTable', function (id) {
alert(id)
});
});
</script>
以上代碼簡單易懂,jquery通過AJAX從后臺獲取信息并顯示在表格上的實現(xiàn)類就這樣完成了,希望大家喜歡。
- Jquery ajax請求導(dǎo)出Excel表格的實現(xiàn)代碼
- JQuery Ajax動態(tài)生成Table表格
- bootstrap jquery dataTable 異步ajax刷新表格數(shù)據(jù)的實現(xiàn)方法
- 用Jquery實現(xiàn)可編輯表格并用AJAX提交到服務(wù)器修改數(shù)據(jù)
- JQuery通過AJAX從后臺獲取信息顯示在表格上并支持行選中
- jQuery+Ajax實現(xiàn)表格數(shù)據(jù)不同列標題排序(為表格注入活力)
- JQuery DataTable刪除行后的頁面更新利用Ajax解決
- jQuery DataTables插件自定義Ajax分頁實例解析
- jQuery ajax動態(tài)生成table功能示例
- jQuery+ajax實現(xiàn)動態(tài)添加表格tr td功能示例
相關(guān)文章
Ajax獲取php返回json數(shù)據(jù)動態(tài)生成select下拉框的實例
今天小編就為大家分享一篇Ajax獲取php返回json數(shù)據(jù)動態(tài)生成select下拉框的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08
細數(shù)Ajax請求中的async:false和async:true的差異
下面小編就為大家?guī)硪黄殧?shù)Ajax請求中的async:false和async:true的差異。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02
AJAX入門之深入理解JavaScript中的函數(shù)
AJAX入門之深入理解JavaScript中的函數(shù)...2007-02-02
Ajax中數(shù)據(jù)傳遞的另一種模式 javascript Object Notation思想(JSON)
JSON是一個誘人的技術(shù),準備做一個大量的試用。希望屆時可以獲取大的性能提高。2010-12-12

