ajaxfifth.js
"use strict";
import {$} from "./modules/nQuery.js";
import {Ajax} from "./modules/Ajax.js";
/*
* Event handler for fortune button - tests responseText
*/
let getNewContent = function() {
let req = Object.create(Ajax);
req.init();
req.getFile("examplejson2g.json", txtHandler);
}
/*
* readystatechange/load event handler
* aka callback function
* for the above AJaX
*/
let txtHandler = function(e) {
/* ajax load event
* puts received text
* onto the dom
* into the dom
*/
let obj = JSON.parse(e.target.responseText); // objectify response
// and use it
let txt = document.createTextNode(`Byen ${obj[1].name} har ${obj[1].population} indbyggere`);
let p = document.createElement("p");
p.appendChild(txt);
$("new").appendChild(p);
}
/*
* Listen to the button
*/
let showStarter = function () {
$("fortune").addEventListener("click", getNewContent);
}
window.addEventListener("load", showStarter); // kick off JS
ajaxfifth.html
In this example the JSON file is the same as in the previous example.
<!doctype html>
<html>
<head>
<meta charset='utf-8'/>
<title>AJaX</title>
<script type="module" src="ajaxfifth.js"></script>
</head>
<body>
<h1>Niels' AJaX Demo 5</h1>
<section>
<h2>Get JSON from Server</h2>
<div id='new'></div>
<p><button id='fortune'>JSON</button></p>
</section>
</body>
</html>