37.4. The Third Example - Using the Object

Example 37.6. The Application JavaScript, ajaxthird.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('example.txt', 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'));    // debug only
    let para = document.createElement('p');                     
    let txt = document.createTextNode(e.target.responseText);
    para.appendChild(txt);                                      // response to p
    $('new').appendChild(para);                                 // p into page dom
}

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

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

        

Example 37.7. The Wanted Resource, example.txt
Here is a fortune cookie with your lotto numbers.
You don't really believe in fortunes, do you?
Well, anyway, here they are: 2 4 7 11 15 19 25

        

Example 37.8. The Application HTML5 - ajaxthird.html
<!doctype html>
<html>
    <head>
        <meta charset='utf-8'/>
        <title>AJaX</title>
        <script type="module" src="ajaxthird.js"></script> 
    </head>
    <body>
        <h1>Niels' AJaX Demo 3</h1>
        <section>
            <h2>Get Fortune Text from Server</h2>
            <div id='new'></div>
            <p><button id='fortune'>Fortune</button></p>
        </section>
    </body>
</html>

        

Click here!