The Fourth Example - Now with JSON - Debugging Mode

Example 36.21. The Application JavaScript, ajaxfourth.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
     */
    console.log(e.target.getResponseHeader("Content-Type"));
    let pre = document.createElement("pre");                     
    let txt = document.createTextNode(e.target.responseText);
    pre.appendChild(txt);
    $("new").appendChild(pre);
}

/*
 *  Listen to the button
 */
let showStarter = function () {
    $("fortune").addEventListener("click", getNewContent);
}

window.addEventListener("load", showStarter);                   // kick off JS

        

Example 36.22. The Wanted Resource, examplejson2g.txt
[
    {
        "id": "3315",
        "name": "K\u00f8benhavn",
        "population": "495699"
    },
    {
        "id": "3316",
        "name": "\u00c5rhus",
        "population": "284846"
    },
    {
        "id": "3317",
        "name": "Odense",
        "population": "183912"
    },
    {
        "id": "3318",
        "name": "Aalborg",
        "population": "161161"
    },
    {
        "id": "4080",
        "name": "Suburbia",
        "population": "1201"
    },
    {
        "id": "4081",
        "name": "Gotham",
        "population": "1200001"
    },
    {
        "id": "4083",
        "name": "Vejen",
        "population": "7777"
    }
]
        

Example 36.23. The Application HTML5 - ajaxfourth.html
<!doctype html>
<html>
    <head>
        <meta charset='utf-8'/>
        <title>AJaX</title>
        <script type="module" src="ajaxfourth.js"></script> 
    </head>
    <body>
        <h1>Niels' AJaX Demo 4 - debugging display</h1>
        <section>
            <h2>Get JSON from Server</h2>
            <div id='new'></div>
            <p><button id='fortune'>JSON</button></p>
        </section>
    </body>
</html>

        

Click here!