jquery - 如何在 jQuery 中从 JSON 文件中读取单个数据?
问题描述
这是我的代码片段。它可以正常加载数据。但是在加载单个数据时,我对这种方法感到困惑。我的要求是我必须在表头中添加一个按钮。当我单击按钮时,只有它应该显示我的下一个数据,否则它应该保持原样。我是 jQuery 的新手。所以,这可能是一个愚蠢的问题。
<!DOCTYPE html>
<html>
<head>
USING AJAX Calls <br> <br> <br>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
let body = $('#Placeholder').find('tbody');
$("button").click(function(){
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts',
success: function(data) {
data.forEach(d => {
body.append(`
<tr>
<td>${d.id}</td>
<td>${d['title']}</td>
</tr>`);
});
}
});
});
});
</script>
</head>
<body>
<h1>Display Json Placeholder files in tabular format</h1>
<br>
<br>
<!-- <div id="div1"></div> -->
<table id="Placeholder" class="display" style="width:100%" cellspacing="10" cellpadding="10">
<thead>
<tr>
<th>ID</th>
<th>Description</th>
<th>
<button id="AppendNextData">Click here to view next data</button>
</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
解决方案
<!--I have modified your code with your ajax function only you can try, may be this will resolve your issue-->
<!DOCTYPE html>
<html>
<head>
USING AJAX Calls <br> <br> <br>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#AppendNextData").click(function(){
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts',
success: function(data) {
var obj = JSON.parse(data);
var tr;
for (var i = 0; i < obj.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + (i+1) + "</td>");
tr.append("<td>" + obj[i].id + "</td>");
tr.append("<td>" + obj[i].title + "</td>");
$('table').append(tr);
}
}
});
});
});
</script>
</head>
<body>
<h1>Display Json Placeholder files in tabular format</h1>
<br>
<br>
<button id="AppendNextData">Click here to view next data</button>
<table id="table" class="display" style="width:100%" cellspacing="10" cellpadding="10">
<tr>
<th>Sl No.</th>
<th>ID</th>
<th>Description</th>
</tr>
</table>
</body>
</html>
推荐阅读
- javascript - 如何在发光元素模板之间传递数据?
- angular - 如何将值/条目添加到firebase集合中的字段
- ruby-on-rails - Ruby on rails 如何用按钮连接脚本
- python - Speech to Text word level Confidence 不适用于 Python 中的 Google API
- html - Images Not Stacking - HTML & CSS
- python - Quicksort function does not produce the expected output, though partition function does (python)
- php - 使用ajax php发布大量嵌套字段的问题
- sql - Where 子句 SQL (Oracle) 中的案例
- reactjs - React Navigation 5, block back navigation after login
- git - How to create a proper merge commit in git which is also squashed