当前位置:Gxlcms > AJAX > jquery通过AJAX从后台获取信息并显示在表格上的实现类

jquery通过AJAX从后台获取信息并显示在表格上的实现类

时间:2021-07-01 10:21:17 帮助过:45人阅读

在上篇文章给大家介绍了JQuery通过AJAX从后台获取信息显示在表格上并支持行选中 ,现在,抽个时间他们处理了一下,这样就不需要每次写代码了,可以节省大量的时间,具体请看下文:

具体代码如下:

  1. //获取数据并显示数据表格
  2. function GetTableData(tableId,ChlickEvent) {
  3. var table = $(tableId);
  4. var url=table.data('url');
  5. $.ajax({
  6. url: url,
  7. type: 'post',
  8. dataType: 'json',
  9. })
  10. .done(function (json) {
  11. var fileds = new Array();
  12. table.children('thead').children('tr').children('th').each(function (index, el) {
  13. var field = $(this).data('field');
  14. fileds[index] = field;
  15. });
  16. var tbody = '';
  17. $.each(json, function (index, el) {
  18. var tr = "<tr>";
  19. $.each(fileds, function (i, el) {
  20. if (fileds[i]) {
  21. tr += '<td>' + formatJsonData(json[index][fileds[i]]) + '</td>';
  22. }
  23. });
  24. tr += "</tr>";
  25. tbody += tr;
  26. });
  27. table.children('tbody').append(tbody);
  28. if (ChlickEvent) {//如果需要支持行选中事件
  29. table.children('tbody').addClass('sel');
  30. table.children('tbody.sel').children('tr').click(function (event) {
  31. $(this).siblings('tr').removeClass('active');//删除其他行的选中效果
  32. $(this).addClass('active');//增加选中效果
  33. ChlickEvent($(this).children('td:eq(0)').text());//新增点击事件
  34. });
  35. }
  36. }).fail(function () {
  37. alert("Err");
  38. });
  39. }
  40. //格式化JSON数据,比如日期
  41. function formatJsonData(jsondata){
  42. if(jsondata==null){
  43. return '无数据';
  44. }
  45. else if(/\/Date\(\d+\)/.exec(jsondata)){
  46. var date = new Date(parseInt(jsondata.replace("/Date(", "").replace(")/", ""), 10));
  47. return date.toLocaleString();
  48. }
  49. return jsondata;
  50. }

写的非常简单,功能也很少,但是我自己用暂时足够了。满足简单需求。

HTML代码必须以下格式,必须以POST方式获取JSON数据,获取地址写到data-url里,数据列名写到data-field里。

支持点击事件。

用法:

  1. <table id="RoleGroupTable" class="table" data-url="@Url.Action("GetRoleGroups", "Account")">
  2. <thead>
  3. <tr>
  4. <th data-field="ID">ID</th>
  5. <th data-field="Name">名称</th>
  6. <th data-field="Remark">简介</th>
  7. </tr>
  8. </thead>
  9. <tbody></tbody>
  10. </table>
  11. <script>
  12. jQuery(document).ready(function ($) {
  13. GetTableData('#RoleGroupTable', function (id) {
  14. alert(id)
  15. });
  16. });
  17. </script>

以上代码简单易懂,jquery通过AJAX从后台获取信息并显示在表格上的实现类就这样完成了,希望大家喜欢。

人气教程排行