block by Rich-Harris 0af262f1bdebaeebfe2c

XHR demo

Full Screen

index.html

<main>hello <span class='target'>[click me to load my-data.json]</span>!</main>

<script src='get.js'></script>
<script>
	var target = document.querySelector( '.target' );

	target.addEventListener( 'click', function () {
		get( 'my-data.json' )
			.then( JSON.parse )
			.then( function ( data ) {
				target.textContent = data.hello;
			});
	});
</script>

get.js

function get ( url ) {
	return new Promise( function ( fulfil, reject ) {
		var xhr = new XMLHttpRequest();

		xhr.open( 'GET', 'my-data.json' );

		xhr.onload = function () {
			fulfil( xhr.responseText );
		};

		xhr.onerror = reject;

		xhr.send();
	});
}

my-data.json

{
	"hello": "world"
}