我尝试将API与我上传API内容的表格链接起来。之后,我想以下列方式自定义我的表格:
我不知道如何编写此代码。我还是初学者,我对其他函数的AJAX的JQuery没有任何见解。 有人可以帮帮我吗?
到目前为止,这是我的代码:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<h1> Inventory List </h1>
<script>
$(document).ready(function () {
$.getJSON('http://wt.ops.few.uva.nl/api/-----',
function (json) {
var tr;
for (var i = 0; i < json.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + json[i].category + "</td>");
tr.append("<td>" + json[i].name + "</td>");
tr.append("<td>" + json[i].amount + "</td>");
tr.append("<td>" + json[i].location + "</td>");
tr.append("<td>" + json[i].date + "</td>");
$('#table').append(tr);
}
});
});
</script>
<table id= "table">
<tr>
<th> Name of product</th>
<th> Category</th>
<th> Amount</th>
<th> Location</th>
<th> Date</th>
</tr>
<form action="http://wt.ops.few.uva.nl/api/-----" method= "post">
<strong> Add new product </strong> <br>
<label> Name of Product:</label> <input type="text" name="name" /><br/>
<label> Category:</label>
<input list="category" name="category"/>
<datalist id="category">
<option value="Stationery">
<option value="Home and Living">
<option value="Foods and Drinks">
<option value="Clothing and Shoes">
<option value="Technology">
</datalist>
<label>Amount:</label> <input type="text" name= "amount"/><br/>
<label>Location: </label><input type="text" name="location"/><br/>
<label> Date:</label> <input type="text" name="date" /><br/>
<input type= "submit" value="Submit">
</form>
</body>
</html>
答案 0 :(得分:0)
查看此codepen,http://codepen.io/anon/pen/xZXNrX。您只需使用Jquery对您提供的URL执行发布请求,它将处理将其添加到对象数组中。单击按钮,它将弹出Post请求的响应。然后刷新页面以查看您的项目已添加到列表底部。
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<h1> Inventory List </h1>
<button>Add Pears</button>
<script>
$(document).ready(function () {
var data = '{"category": "Fruit", "name": "Pear", "amount": 12, "location": "Amsterdam", "date": "2014-10-05", "id": 20530}'
$("button").click(function(event){
event.preventDefault();
$.post("http://wt.ops.few.vu.nl/api/79fe2e95", data, function(result){
alert("Response from request: " + JSON.stringify(result));
});
});
$.getJSON('http://wt.ops.few.vu.nl/api/79fe2e95',
function (json) {
var tr;
for (var i = 0; i < json.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + json[i].category + "</td>");
tr.append("<td>" + json[i].name + "</td>");
tr.append("<td>" + json[i].amount + "</td>");
tr.append("<td>" + json[i].location + "</td>");
tr.append("<td>" + json[i].date + "</td>");
$('#table').append(tr);
}
});
});
</script>
<table id= "table">
<tr>
<th> Name of product</th>
<th> Category</th>
<th> Amount</th>
<th> Location</th>
<th> Date</th>
</tr>
</table>
</body>
</html>