javascript - 来自 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');
}
});
尝试使用此代码
但我很困惑如何用自定义数据和单独的标题提供我自己的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 标签下并且有标题
解决方案
我相信这就是你想要达到的目标。(除了 $.get() 之外没有 jQuery)。
- 给定一些数据(这里是假博客文章)
- 修改数据是某种方式
- 将修改后的数据放入表中
- 提供带有链接的“操作”列以删除该行
$.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>
推荐阅读
- excel - 如何在 VBA 的下拉列表中选择起始值?
- express - PayPal Express Checkout 运费计算
- spring-boot - 无法启动嵌入式 tomcat 服务器
- javascript - 如果javascript中的键值相同,则合并对象数组
- javascript - 如何连接两个对象数组?
- database - Oracle 审计触发器提示用户问题
- arrays - TypeError:无法读取 null 的属性“upvotes”
- html - 如果我将 Normalize.css 添加为第二个 CSS 样式表或者它会覆盖某些内容,它是否可以正常工作?
- google-cloud-platform - 使用 Google Cloud DataPrep 运行作业的问题 - 用户没有 bigquery.jobs.create - PERMISSION_DENIED
- ios - 如何改变bottomTab的形状