37.9. The Fifth Example - Now with Objectified JSON

Example 37.24. The Application JavaScript, 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

        

Example 37.25. The Application HTML5 - 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>

        

Click here!