首页 > 解决方案 > 来自 Ajax 调用的 JSON 数据

问题描述

我有来自我的函数的 JSOn 数据,我不需要所有数据,也必须根据我得到的数据创建一些数据,有许多外部代码指定如何循环 json 数据并显示它

$.ajax({url: 'page.php',
        data: {id: 1},
        dataType: 'json',
        type:'POST',
        success: function (json) {
            div.html('<table align="left" width="70%" class="table table-striped borderless p-l-xl">'+
                    '<tr>'+
                        '<td>d1</td><td>d2</td><td>Action</td></tr>'+
                        '<tr><td>'+json.d1+'</td><td>'+json.d2+'</td>'+
                        '<td><a href="javascript:;" class="t" data-id="'+ json.id +'" data-sid="'+json.sid+'">Delete</a></td>'+
                    '</tr>'+
                '</table>').removeClass('loading');
            } 
    });

尝试使用此代码

如何使用 jQuery 迭代 JSON 对象

但我很困惑如何用自定义数据和单独的标题提供我自己的href

做了一个小更新

$.each(json,function(index,item){
                $('<table><tr>').append(
                    $("<td>").text(item.d1),
                    $("<td>").text(item.d2),
                    $("<td>").html('<a href="javascript:;" class="d" data-sid="'+ json.id+'" data-id="'+json.id+'">Delete</a></td>')
                ).appendTo(div);
        });

现在它可以工作并为每条记录创建一个单独的记录,并且缺少标题

虽然我希望所有行都应该在一个 TABLE 标签下并且有标题

标签: javascriptjqueryjson

解决方案


我相信这就是你想要达到的目标。(除了 $.get() 之外没有 jQuery)。

  1. 给定一些数据(这里是假博客文章)
  2. 修改数据是某种方式
  3. 将修改后的数据放入表中
  4. 提供带有链接的“操作”列以删除该行

$.get('https://jsonplaceholder.typicode.com/posts', transformData);

function transformData(posts) {
  let tableData = posts.map(post => {
    return {
      id: post.id,
      title: post.title,
      added: 'added'
    }
  });
  makeTable(tableData);
}

function deleterow(el) {
  alert('Deleting row with id: ' + el.dataset.id);
}

function makeTable(data) {
  var table = document.createElement("table");
  table.style.border = "1px";
  var headerRow = document.createElement("thead");
  headerRow.style.backgroundColor = "#ccc";

  Object.keys(data[0]).forEach(key => {
    let headerCol = document.createElement("td");
    headerCol.textContent = key;
    headerRow.appendChild(headerCol);
  });
  let actionCol = document.createElement('td');
  actionCol.textContent = 'Action';
  headerRow.appendChild(actionCol);
  table.appendChild(headerRow);

  data.forEach(item => {
    let row = document.createElement("tr");
    Object.keys(item).forEach(key => {
      let col = document.createElement("td");
      col.textContent = item[key];
      row.appendChild(col);
    });
    let action = document.createElement("a");
    action.href = 'javascript:void(0);';
    action.textContent = 'Delete';
    action.setAttribute("onclick", 'deleterow(this)');
    action.dataset.id = item.id;
    action.dataset.title = item.title;
    action.dataset.added = item.added;
    row.appendChild(action);
    table.appendChild(row);
  });
  document.body.appendChild(table);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


推荐阅读