Skip to content

Instantly share code, notes, and snippets.

@ericlaw1979
Created Sep 25, 2020
Embed
What would you like to do?
<!doctype html>
<head><title>Fetch tests</title>
<script>
function stateChanged()
{
if (this.readyState==4 || this.readyState=="complete")
{
let data = this.status + " " + this.statusText +"\n" + this.getAllResponseHeaders() + "----------------\n" + this.responseText;
console.log(data);
}
}
function doGet(u){
let xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = stateChanged;
xmlhttp.open("GET", u, true);
xmlhttp.send();
}
fetch("json.json").then(e=>{
console.log("Fetch returned: " + e.ok + " (status="+ e.status + ")");
e.json().then(o=>console.log(JSON.stringify(o))).catch(err=> {console.log("Caught an Error when retrieving empty body json(): "+ err);} );
}
);
fetch("sub/json.json").then(e=>{
console.log("Fetch returned: " + e.ok + " (status="+ e.status + ")");
e.json().then(o=>console.log(JSON.stringify(o))).catch(err=> {console.log("Caught an Error when retrieving empty body json(): "+ err);} );
}
);
fetch("file:///C:/src/json.json").then(e=>{
console.log("Returned: " + e.ok + "("+ e.status + ")");
e.json().then(o=>console.log(JSON.stringify(o))).catch(err=> {console.log("Caught an Error when retrieving json(): "+ err);} );
}
);
doGet("json.json");
doGet("sub/json.json");
doGet("/src/json.json");
</script>
</head>
<body>
Check the DevTools console
<br />
<h1>Documentation</h1>
<a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch">Docs</a>
<iframe src="json.json"></iframe>
<iframe src="sub/json.json"></iframe>
<iframe src="/src/json.json"></iframe>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment