87 lines
2.5 KiB
HTML
87 lines
2.5 KiB
HTML
<!DOCTYPE html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<title>Local Site — Data (fetch + XHR)</title>
|
|
<link rel="stylesheet" href="assets/site.css">
|
|
</head>
|
|
<body>
|
|
<header>
|
|
<h1>Data Page</h1>
|
|
<nav>
|
|
<a href="index.html">Home</a>
|
|
<a href="data.html">Data</a>
|
|
</nav>
|
|
</header>
|
|
<main>
|
|
<h2>fetch() a local JSON file</h2>
|
|
<pre id="fetch-out">fetch() not started.</pre>
|
|
|
|
<h2>XMLHttpRequest a local JSON file</h2>
|
|
<pre id="xhr-out">XHR not started.</pre>
|
|
|
|
<h2>fetch() a file in a subdirectory</h2>
|
|
<pre id="fetch-sub-out">sub fetch not started.</pre>
|
|
|
|
<h2>fetch() a missing file (expect rejection)</h2>
|
|
<pre id="fetch-missing-out">missing fetch not started.</pre>
|
|
|
|
<h2>fetch() with a query string</h2>
|
|
<pre id="fetch-query-out">query fetch not started.</pre>
|
|
</main>
|
|
<script>
|
|
(async function () {
|
|
// 1. fetch a sibling JSON file
|
|
try {
|
|
const r = await fetch('assets/data.json');
|
|
const j = await r.json();
|
|
document.getElementById('fetch-out').textContent =
|
|
'OK status=' + r.status + '\n' + JSON.stringify(j, null, 2);
|
|
} catch (e) {
|
|
document.getElementById('fetch-out').textContent = 'ERROR: ' + e.message;
|
|
}
|
|
|
|
// 2. XHR a sibling JSON file
|
|
try {
|
|
const xhr = new XMLHttpRequest();
|
|
xhr.open('GET', 'assets/data.json', false);
|
|
xhr.send(null);
|
|
document.getElementById('xhr-out').textContent =
|
|
'OK status=' + xhr.status + '\n' + xhr.responseText;
|
|
} catch (e) {
|
|
document.getElementById('xhr-out').textContent = 'ERROR: ' + e.message;
|
|
}
|
|
|
|
// 3. fetch a file in a subdirectory
|
|
try {
|
|
const r = await fetch('subdir/sub.json');
|
|
const t = await r.text();
|
|
document.getElementById('fetch-sub-out').textContent =
|
|
'OK status=' + r.status + '\n' + t;
|
|
} catch (e) {
|
|
document.getElementById('fetch-sub-out').textContent = 'ERROR: ' + e.message;
|
|
}
|
|
|
|
// 4. fetch a missing file
|
|
try {
|
|
const r = await fetch('assets/does-not-exist.json');
|
|
document.getElementById('fetch-missing-out').textContent =
|
|
'status=' + r.status + ' ok=' + r.ok;
|
|
} catch (e) {
|
|
document.getElementById('fetch-missing-out').textContent = 'ERROR: ' + e.message;
|
|
}
|
|
|
|
// 5. fetch with a query string (should be ignored for file://)
|
|
try {
|
|
const r = await fetch('assets/data.json?cache=bust');
|
|
const t = await r.text();
|
|
document.getElementById('fetch-query-out').textContent =
|
|
'OK status=' + r.status + '\n' + t;
|
|
} catch (e) {
|
|
document.getElementById('fetch-query-out').textContent = 'ERROR: ' + e.message;
|
|
}
|
|
})();
|
|
</script>
|
|
</body>
|
|
</html>
|