JavaScript: implementing getJSON from scratch

by antouank

HTML

<div id="tweet"></div>

JavaScript

(function() {
    var Lib = {
        ajax: {
            xhr: function() {
                var instance = new XMLHttpRequest();
                return instance;
            },
            getJSON: function(options, callback) {
                var xhttp = this.xhr();
                options.url = options.url || location.href;
                options.data = options.data || null;
                callback = callback ||
                function() {};
                options.type = options.type || 'json';
                var url = options.url;
                if (options.type == 'jsonp') {
                    window.jsonCallback = callback;
                    var $url = url.replace('callback=?', 'callback=jsonCallback');
                    var script = document.createElement('script');
                    script.src = $url;
                    document.body.appendChild(script);
                }
                xhttp.open('GET', options.url, true);
                xhttp.send(options.data);
                xhttp.onreadystatechange = function() {
                    if (xhttp.status == 200 && xhttp.readyState == 4) {
                        callback(xhttp.responseText);
                    }
                };
            }
        }
    };

    window.Lib = Lib;
})()


    Lib.ajax.getJSON({
        url: 'https://api.twitter.com/1/statuses/user_timeline.json?&screen_name=antouank&callback=?&count=1',
        type: 'jsonp'
    }, function(tweet) {
        document.querySelector('#tweet').innerHTML = tweet[0].text;
    });