JSON data fetching

Hi Folks,

HTML code:

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Untitled Document</title>
    </head>

    <body>
    <script>
    var xhr = new XMLHttpRequest(); //Create XMLHttpRequest object
    	xhr.onload =function() { //When readystate changes
    		if(xhr.status === 200) { // If server status was ok
    			responseObject = JSON.parse(xhr.responseText);
    			// BUILD UP STRING WITH NEW CONTENT (could also use DOM manipulation)
    	var newContent = '';
    	for (var i = 0; i < responseObject.events.length; i++){
    		newContent += '<div class="event">';
    		newContent += '<img src="' + responseObject.events[i].map +'"';
    		newContent += 'alt="' + responseObject.events[i].location + '" />';
    		newContent += ' <p><b>' + responseObject .events[i] .location+ '</b><br>';
    		newContent += responseObject.events[i].date + '</p>';
    		newContent += '</div>';
    	}
    		document.getElementById('content').innerHTML = newContent;
    		}
    		};
    	xhr.open("GET", "data.json", true);
    	xhr.send(null);
    </script>
    <div id="content"></div>
    </body>
    </html>

JSON data:

[
	{
		"events" : [
				{ "location" : "San Francisco, CA" , "date" : "May l ", "map" : "img/01.png" },
				{ "location": "Austin, TX", "date": "May 15", "map" : "img/02.png" },
				{ "location" : "New York, NY", "date" : "May 30", "map" : "img/03.png" },
					
		]
		
	}
]

output:

    '; newContent += '
    ' + responseObject .events[i] .location+ '
    '; newContent += responseObject.events[i].date + '

    '; newContent += ''; } document.getElementById('content').innerHTML = newContent; } }; xhr.open("GET", "data.json", true); xhr.send(null);
    newContent += '
    '; newContent += ''; newContent += '
    ' + responseObject .events[i] .location+ '
    '; newContent += responseObject.events[i].date + '

    '; newContent += '
    '; } document.getElementById('content').innerHTML = newContent; } }; xhr.open("GET", "data.json", true); xhr.send(null);

can anyone tell whether I am doing anything wrong here and I am new to AJAX call?

Shouldn’t it be responseObject[0].events? It seems that your JSON is a list of objects.

Couldn’t get you.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.