JavaScript 2022

Term 3 Wednesday

May - July 2022

This site will be updated live during the sessions

Week 9 5 Fetch

		
001window.onload = function(){
		
002	showStuff('_json.json',document.querySelector('#result'))
		
003}
		
004
		
005function showStuff(whereFrom, whereTo) {
		
006    fetch(whereFrom)
		
007        .then(response => 
		
008		{
		
009            if (!response.ok) {
		
010                throw new Error("Failed with HTTP code " + response.status);
		
011            }
		
012            return response;
		
013        })
		
014        .then(result => result.json())
		
015        .then(data => 
		
016		{
		
017            console.log(data);
		
018			// format (as HTML) object data
		
019			const html = createDisplayDataFromNonNestedObject(data);
		
020			
		
021			// insert formatted data into the DOM
		
022			insertIntoHTML(html, whereTo);
		
023        });
		
024}
		
025
		
026function createDisplayDataFromNonNestedObject(obj)
		
027{
		
028	let html = '';
		
029	for(item in obj)
		
030	{
		
031		
		
032		html += `<p>${capitalise(item)}: ${capitalise(obj[item])}</p>`;
		
033	}
		
034	return html;
		
035}
		
036
		
037function insertIntoHTML(html, elem = document.querySelector('main'))
		
038{	
		
039		elem.insertAdjacentHTML('afterbegin', html);
		
040}
		
041
		
042function capitalise(str)
		
043{
		
044	return str[0].toUpperCase() + str.slice(1).toLowerCase();
		
045}
		
046
		
047