<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
table, td, th {
border: 1px solid black;
}
table {
border-collapse: collapse;
width: 100%;
}
td {
height: 50px;
vertical-align: bottom;
}
</style>
</head>
<body>
<table id =101>
<tr>
<th>id</th>
<th>name</th>
<th>category</th>
<th>color</th>
</tr>
<div>
</div>
</table>
<script>
var url = "http://34.201.147.118:3001/getAllData";
var xhr = new XMLHttpRequest()
xhr.open('GET', url, true)
xhr.onload = function () {
var users = JSON.parse(xhr.responseText);
console.log(users)
if (xhr.readyState == 4 && xhr.status == "200") {
var obj= users
console.table(obj);
var tbl=$("#101").attr("id","mytable");//The attr() method set the id attribute to mytable this method is used to return the attribute value, it returns the value of the FIRST matched element.When this method is used to set attribute values,
$("#div1").append(tbl);
for(var i=0;i<obj.length;i++)
{
console.log(obj.length)
var tr="<tr>";
var td1="<td>"+obj[i]["id"]+"</td>";
var td2="<td>"+obj[i]["name"]+"</td>";
var td3="<td>"+obj[i]["category"]+"</td>";
var td4 ="<td>"+obj[i]["color"]+"</td></tr>";
$("#mytable").append(tr+td1+td2+td3+td4);
}
console.table(users);
} else {
console.error(users);
}
}
</script>
</body>
</html>
答案 0 :(得分:1)
尝试此代码并在循环中更新您的参数。
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script>
<style>
table, td, th {
border: 1px solid black;
}
table {
border-collapse: collapse;
width: 100%;
}
td {
height: 50px;
vertical-align: bottom;
}
</style>
</head>
<body>
<table id='mytable'>
<tr>
<th>id</th>
<th>name</th>
<th>category</th>
<th>color</th>
</tr>
<div>
</div>
</table>
<script>
$(document).ready(function(){
var url = "http://34.201.147.118:3001/getAllData";
$.getJSON(url, function( data ) {
var obj = data['AllData'];
for(var i=0;i<obj.length;i++)
{
var tr ="<tr>"+
"<td>"+obj[i]["id"]+"</td>"+
"<td>"+obj[i]["name"]+"</td>"+
"<td>"+obj[i]["category"]+"</td>"+
"<td>"+obj[i]["color"]+"</td></tr>";
$("#mytable").append(tr);
}
});
});
</script>
</body>
</html>
答案 1 :(得分:0)
考虑一下;-)我认为你应该这样做。
var data = { //A object
get: function() { //Your get method
var url = "http://34.201.147.118:3001/getAllData";
$.ajax({
url: url,
type: 'GET',
success: function(responseText) {
var users = JSON.parse(responseText);
this.output(users); //Call output method
}.bind(this),
error: function(response) {
console.error(response);
}
});
},
output: function(users) { //Your output method
console.log(users.length);
users.forEach(function(user) {
var tr = "<tr>";
var td1 = "<td>" + user.id + "</td>";
var td2 = "<td>" + user.name + "</td>";
var td3 = "<td>" + user.category + "</td>";
var td4 = "<td>" + user.color + "</td></tr>";
$("#mytable").append(tr + td1 + td2 + td3 + td4);
});
}
}
data.get();