I have the following Javascript code:
var request = new XMLHttpRequest();
request.open("GET", "http://localhost:8080/CarSales/rest/cars", true);
request.onreadystatechange = function(){
if(request.readyState === XMLHttpRequest.DONE){
var status = request.status;
if (status === 0 || (status >= 200 && status < 400)){
var cars = JSON.parse(request.responseText);
var output = "";
for(var i in cars){
output ='<tr><td>'+cars[i].make+'</td><td>'+cars[i].model+'</td><td>'+cars[i].year+'</td> <td>'+cars[i].engine+'</td></tr>';
}
document.getElementById('table-body').innerHTML = output;
}else{
console.log("error");
}
}
};
request.send();
and the following HTML:
<!DOCTYPE html>
<html>
<head>
<script src="js/Q4.js"></script>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<table id="table">
<tr>
<th>Make</th>
<th>Model</th>
<th>Year</th>
<th>Engine</th>
</tr>
<tbody id="table-body"></tbody>
</table>
</body>
</html>
Currently it outputs the last object of the json data in the table correctly: https://i.sstatic.net/V73pC.png
How do I get the JS code to output all json objects into the table? Perhaps by changing the for loop to iterate through the json data?