Click here to Skip to main content
15,889,862 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I want to make a program that gives a list of the people in space.



This is what i want the output to be like:

name1 name2 name3

but this is the result:

name1 name2 name3 name1 name2 name3

What do i do?
thanks

What I have tried:

HTML
<div id="space_astronauts">
    <span id="child_1"></span>
</div>

JavaScript
var space = new XMLHttpRequest();
space.open("GET", "http://api.open-notify.org/astros.json", "jsonp");
space.send(null);
space.onreadystatechange = function() {
	var res = JSON.parse(space.response);
	
	var totalPeople = res.number;
	for (i = 0; i < totalPeople; i++) {
		var pElement = document.getElementById("space_astronauts");
		var firstChild = pElement.firstChild;
		var astronautsElement = document.createElement("a");
   		var txt = document.createTextNode(res.people[i].name + " ");
   		astronautsElement.appendChild(txt);

   		pElement.insertBefore(astronautsElement, firstChild);
   	}
}
Posted
Updated 11-Feb-17 19:36pm
Comments
Peter Leow 11-Feb-17 22:50pm    
show an example of the content of space.response? and what is res.number?
Karthik_Mahalingam 12-Feb-17 1:37am    
http://api.open-notify.org/astros.json

1 solution

if (this.readyState == 4 && this.status == 200) {
the above condition is missing in the response, which leads to print the data twice.

var space = new XMLHttpRequest();
       space.open("GET", "http://api.open-notify.org/astros.json", "jsonp");
       space.send(null);
       space.onreadystatechange = function () {
           if (this.readyState == 4 && this.status == 200) {
               var res = JSON.parse(space.response);

               var totalPeople = res.number;
               for (i = 0; i < totalPeople; i++) {
                   var pElement = document.getElementById("space_astronauts");
                   var firstChild = pElement.firstChild;
                   var astronautsElement = document.createElement("a");
                   var txt = document.createTextNode(res.people[i].name + " ");
                   astronautsElement.appendChild(txt);

                   pElement.insertBefore(astronautsElement, firstChild);
               }
           }
       }
 
Share this answer
 
Comments
Peter Leow 12-Feb-17 1:40am    
5ed!
Karthik_Mahalingam 12-Feb-17 1:41am    
Thanks Peter Leow
Member 12995525 12-Feb-17 6:46am    
Thanks, it worked !
Karthik_Mahalingam 12-Feb-17 6:52am    
Welcome

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900