PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

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

亚连
亚连 原创
2018-05-24 17:34:19 2098浏览

jquery通过ajax从后台获取信息并显示在表格上的实现类,单独写出来,这样程序员,不需要每次写代码了,可以节省大量的时间,感兴趣的朋友一起来看看吧

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

具体代码如下:

//获取数据并显示数据表格
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 += &#39;<td>&#39; + formatJsonData(json[index][fileds[i]]) + &#39;</td>&#39;;
    }
   });
   tr += "</tr>";
   tbody += tr;
  });
  table.children(&#39;tbody&#39;).append(tbody);
  if (ChlickEvent) {//如果需要支持行选中事件
   table.children(&#39;tbody&#39;).addClass(&#39;sel&#39;);
   table.children(&#39;tbody.sel&#39;).children(&#39;tr&#39;).click(function (event) {
    $(this).siblings(&#39;tr&#39;).removeClass(&#39;active&#39;);//删除其他行的选中效果
    $(this).addClass(&#39;active&#39;);//增加选中效果
    ChlickEvent($(this).children(&#39;td:eq(0)&#39;).text());//新增点击事件
   });
  }
 }).fail(function () {
  alert("Err");
 });
}
//格式化JSON数据,比如日期
function formatJsonData(jsondata){
 if(jsondata==null){
  return &#39;无数据&#39;;
 }
 else if(/\/Date\(\d+\)/.exec(jsondata)){
  var date = new Date(parseInt(jsondata.replace("/Date(", "").replace(")/", ""), 10));
  return date.toLocaleString();
 }
 return jsondata;
}

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

HTML代码必须以下格式,必须以POST方式获取JSON数据,获取地址写到data-url里,数据列名写到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(&#39;#RoleGroupTable&#39;, function (id) {
  alert(id)
 });
 });
</script>

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

JQuery Ajax动态生成Table表格

浅析Asp.net MVC 中Ajax的使用

基于h5 ajax实现手机定位

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。