如何使用jQuery更新表

时间:2015-01-20 20:54:31

标签: javascript jquery html ajax json

我正在尝试根据从ajax请求收到的输入动态更新下面的html表的行,该请求返回一个JSON对象。

如果我得到多个json对象,那么在网页上打印它就成了一个问题。我正在寻找可能的最佳解决方案,在这种情况下使用jQuery动态更新我的表?例如,如果我得到10个对象,我只想显示5,其余可能是下一页链接?有人可以指导我应该研究什么?

jQuery Ajax

<script>
        $.ajax({
            url: 'http://localhost/getData/USSOUTH/',
            async: false,
            dataType: 'json',
            success: function(data) {

                for (var i in data) {

                    var USERNAME = data[i].USERNAME;
                    var EMAIL = data[i].EMAIL;
                    var PASSWORD = data[i].PASSWORD;
                    var ACTIVE = data[i].ACTIVE;

                }
            }
        });
</script>

HTML BODY

<body>

<div class="wrapper">

  <div class="table">

    <div class="row header blue">
      <div class="cell">
        Username
      </div>
      <div class="cell">
        Email
      </div>
      <div class="cell">
        Password
      </div>
      <div class="cell">
        Active
      </div>
    </div>

    <div class="row">
      <div class="cell">
        ninjalug
      </div>
      <div class="cell">
        misterninja@hotmail.com
      </div>
      <div class="cell">
        ************
      </div>
      <div class="cell">
        Yes
      </div>
    </div>

  </div>

</div>

</body>

3 个答案:

答案 0 :(得分:3)

我有点简化了代码,但你会得到要点并且可以修改它以适用于你的特定代码(我不能用代码片段做json,所以我模拟了一个名为jsonData的数组变量<) / p>

$(document).ready(function() {
    var jsonData = [
        { 'name': 'name2', 'email':'email2', 'content':'content2' },
        { 'name': 'name3', 'email':'email3', 'content':'content3' },
        { 'name': 'name4', 'email':'email4', 'content':'content4' },
        { 'name': 'name5', 'email':'email5', 'content':'content5' },
        { 'name': 'name6', 'email':'email6', 'content':'content6' },
        { 'name': 'name7', 'email':'email7', 'content':'content7' },
        { 'name': 'name8', 'email':'email8', 'content':'content8' }
    ];
    $('.add').on('click', function() {
        console.log('click');
        var length = jsonData.length;
        if (length > 5 ) { length = 5; } //limit to 5
        for (var i = 0; i < length; i++) {
            var clone = $('#template').clone(true).attr('id', '');
            clone.find('.name').html(jsonData[i]['name']);
            clone.find('.email').html(jsonData[i]['email']);
            clone.find('.content').html(jsonData[i]['content']);
            clone.appendTo('table');
        }
    });
});
td {
  border:1px solid black;
  padding:2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<a href="#" class="add">add</a>
<table>
    <tr id="template" class="dataRow">
        <td class="name">Name1</td>
        <td class="email">Email1</td>
        <td class="content">Content1</td>
    </tr>
</table>

答案 1 :(得分:1)

如果它支持分页,你可以检查AJAX服务文档,它的响应只包含5条记录,还有一个指标,表示还有更多。这样,您可以按照与第一个请求类似的方式请求显示接下来的5条记录。

如果该服务不支持分页,那么您可以使用属性style="display: none;"隐藏前5个以上的任何记录,并显示导航链接NEXT&amp;以前“滚动”结果。

// Data will be replaced with your Json call
var data = [
  {'username': 'name1', 'email':'email1', 'password':'password1', 'active':'active1' },
  {'username': 'name2', 'email':'email2', 'password':'password2', 'active':'active2' },
  {'username': 'name3', 'email':'email3', 'password':'password3', 'active':'active3' },
  {'username': 'name4', 'email':'email4', 'password':'password4', 'active':'active4' },
  {'username': 'name5', 'email':'email5', 'password':'password5', 'active':'active5' },
  {'username': 'name6', 'email':'email6', 'password':'password6', 'active':'active6' },
  {'username': 'name7', 'email':'email7', 'password':'password7', 'active':'active7' },
  {'username': 'name8', 'email':'email8', 'password':'password8', 'active':'active8' },
  {'username': 'name9', 'email':'email9', 'password':'password9', 'active':'active9' },
  {'username': 'name10','email':'email10','password':'password10','active':'active10'},
  {'username': 'name11','email':'email11','password':'password11','active':'active11'},
  {'username': 'name12','email':'email12','password':'password12','active':'active12'}
];

var MAX_ROWS = 5;
var totalRows = 0;
var page = 0;

$(document).ready(function() {
  // display first 5 rows
  var $templateRow = $('#templateRow');
  $.each(data, function(i, obj) {
    var $row = $templateRow.clone().removeAttr('id')
    // copy data
    $row.find('*[data-name]').html(obj.username);
    $row.find('*[data-email]').html(obj.email);
    $row.find('*[data-pass]').html(obj.password);
    $row.find('*[data-active]').html(obj.active);
    $('.table').append($row);
  });
  // Navigation part
  page = 0;
  totalRows = data.length;
  showRows();
  displayNext();

  // Navigation handler
  $('*[data-prev-lnk]').on('click', function(e) {
    e.preventDefault();
    page--;
    displayPrev();
    displayNext();
    showRows()
  });

  $('*[data-next-lnk]').on('click', function(e) {
    e.preventDefault();
    page++;
    displayPrev();
    displayNext();
    showRows();
  });
});

function displayPrev() {
  if (page > 0)
    $('*[data-prev-lnk]').show();
  else
    $('*[data-prev-lnk]').hide();
}

function displayNext() {
  var currRow = (page+1) * MAX_ROWS;
  if (currRow >= totalRows)
    $('*[data-next-lnk]').hide();
  else
    $('*[data-next-lnk]').show();
}

function showRows() {
  var startRow = page * MAX_ROWS;
  var counter = 0;
  $('.row').each( function() {
    if (! ($(this).attr('id') || $(this).hasClass('header'))) {
      if (counter < startRow || counter >= startRow + MAX_ROWS) {
        $(this).hide();
      }
      else {
        $(this).show();
      }
      counter++;
    }
  });
}
div.table {border: 1px solid black; display: table; width: 500px;}
div.row {border: 1px solid black; display: table-row; }
div.cell {border: 1px solid black; display: table-cell; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="wrapper">
  <div class="table">
    <div class="row header blue">
      <div class="cell">Username</div>
      <div class="cell">Email</div>
      <div class="cell">Password</div>
      <div class="cell">Active</div>
    </div>
    <div id="templateRow" class="row" style="display:none;">
      <div class="cell" data-name=''></div>
      <div class="cell" data-email=''></div>
      <div class="cell" data-pass=''></div>
      <div class="cell" data-active=''></div>
    </div>
  </div>
  <br/><a href='#' data-prev-lnk='' style='display:none'>Previous</a>
  <br/><a href='#' data-next-lnk='' style='display:none'>Next</a>
</div>

答案 2 :(得分:0)

让我们使用theadtbody来更好地使用,并为下一组结果添加按钮。

HTML:

<body>

<div class="wrapper">

  <button id ="nextPage" value ="Next page">
  <div class="table">
    <thead class="row header blue">
      <div class="cell">
        Username
      </div>
      <div class="cell">
        Email
      </div>
      <div class="cell">
        Password
      </div>
      <div class="cell">
        Active
      </div>
    </thead>

    <tbody>
    <div class="row">
      <div class="cell">
        ninjalug
      </div>
      <div class="cell">
        misterninja@hotmail.com
      </div>
      <div class="cell">
        ************
      </div>
      <div class="cell">
        Yes
      </div>
    </div>
    </tbody>

  </div>

</div>

</body>

在JS中将函数分配给按钮,它将显示接下来的5条记录:

var results = "";
$.ajax({
    url: 'http://localhost/getData/USSOUTH/',
    async: false,
    dataType: 'json',
    success: function(data) {
        results = data;
        showResults(results);

    }
});

//function for showing results
function showResults(data)
{
    var rows = $('tbody .row').length; // get number of already displayed records
    for (i = rows; i<=from+4,i++;) //add next 5 records
    {
        var content = '\
            <div class="row">\
                <div class="cell">\
                    '+data[i].USERNAME+'\
                </div>\
                <div class="cell">\
                    '+data[i].EMAIL+'\
                </div>\
                <div class="cell">\
                    '+data[i].PASSWORD+'\
                </div>\
                <div class="cell">\
                    '+data[i].ACTIVE+'\
                </div>\
            </div>';
        $('tbody .row:last').after(content);
    }
}

$("nextPage").click(function(){
    showResults(results);
});