所以我有一个包含FORM元素的表:
<table id="example" class="sortable">
<caption><h3><strong>Product inventory list</strong></h3></caption>
<thead>
<tr>
<th>Name</th>
<th>Category</th>
<th>Amount</th>
<th>Location</th>
<th>Purchase date</th>
</tr>
</thead>
<tfoot>
<form id="myForm" action="http://wt.ops.few.vu.nl/api/xxxxxxxx" method="get">
<td>
<input type="text" name="name" required>
</td>
<td>
<input type="text" name="category" required>
</td>
<td>
<input type="number" name="amount" required>
</td>
<td>
<input type="text" name="location" required>
</td>
<td>
<input type="date" name="date" required>
</td>
<td>
<input type="submit" value="Submit">
</td>
</form>
</tfoot>
</table>
我填写的信息会发送到我的API链接,但现在我需要直接在表格中附上我填写的信息。
我知道我可以发送一个AJAX GET请求,以获取存储在API中的信息,但是如何将返回的JSON数据插入表中?
答案 0 :(得分:0)
您可以获取
的值<input id= "nameid" type="text" name="name" required>
与
var value = $("#nameid").val();
或用
设置$("#nameid").val("myname");
答案 1 :(得分:0)
您可以使用jQuery ready或按钮单击事件来加载数据。下面的代码片段演示了加载HTML文档后自动加载数据。希望这个答案!
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Product Inventory List</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<table id="products" class="sortable" border='1'>
<caption><h3><strong>Product inventory list</strong></h3></caption>
<tr>
<th>Name</th>
<th>Category</th>
<th>Amount</th>
<th>Location</th>
<th>Purchase date</th>
</tr>
</table>
<script>
var api = 'http://example.com/api/v1/products';
$(document).ready(function(){
jQuery.support.cors = true;
$.ajax(
{
type: "GET",
url: api + '/products',
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (data) {
var trHTML = '';
$.each(data.products, function (i, item) {
trHTML += '<tr><td>' + data.products[i].name + '</td><td>' + data.products[i].category + '</td><td>' + data.products[i].amount + '</td><td>' + data.products[i].location + '</td><td>' + data.products[i].pdate + '</td></tr>';
});
$('#products').append(trHTML);
},
error: function (msg) {
alert(msg.responseText);
}
});
})
</script>
</body>
</html>