1

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?

1 Answer 1

1

You have missed to append on every loop. just add after output += ""; its not appending that's the reason displaying only last loop value.

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>';
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.