Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ericlaw1979
Last active November 30, 2023 15:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericlaw1979/d0978f7061ded8c61fa77d94cde2fd82 to your computer and use it in GitHub Desktop.
Save ericlaw1979/d0978f7061ded8c61fa77d94cde2fd82 to your computer and use it in GitHub Desktop.
<!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("../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>
@ericlaw1979
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment