JavaScript 2022

Term 3 Wednesday

May - July 2022

This site will be updated live during the sessions

Week 9 4 Ajax

		
001window.onload = getJsonStuff;
		
002
		
003let xhr = false;
		
004
		
005function getJsonStuff() {
		
006	if (window.XMLHttpRequest) {
		
007		xhr = new XMLHttpRequest();
		
008	} 
		
009	if (xhr) {
		
010		xhr.open("GET", '_json.json');
		
011		xhr.send(); 
		
012		xhr.onreadystatechange = functionToRunOnChange; 
		
013	} else {
		
014		console.log("Error. Could not perform the stated request");
		
015		//document.getElementById("statusmessage").innerHTML = "Error. Could not perform the stated request";
		
016	}	
		
017}
		
018
		
019function functionToRunOnChange() {
		
020	if (xhr.readyState == 4) 
		
021	{
		
022	    if (xhr.status == 200) 
		
023		{
		
024		    const data = JSON.parse(xhr.responseText); 
		
025			let dataText = "";
		
026			for (let item in data) 
		
027			{
		
028				dataText += `<p>${item}: ${data[item]}</p>`;
		
029			} 
		
030			document.getElementById("result").innerHTML = dataText;	
		
031		}			
		
032	}		
		
033}
		
034