Cross-Domain AJAX

HTML

<div id="header"></div>
<ol id="link-list">
    <li><a href="/echo/html/" data-ajax-type="POST">HTML POST: same origin</a> [/echo/html/]</li>
    <li><a href="http://www.w3schools.com/ajax/ajax_info.txt">HTML GET: Different origin</a> [http://www.w3schools.com/ajax/ajax_info.txt]</li>
    <li><a href="https://a.uguu.se/slx147peCEu7.json" data-ajax-type="JSONP">JSONP GET: different origin</a> [http://jsfiddle.net]</li>
    <li><a href="http://jsonmoon.jsapp.us/">JSON GET: different origin</a> [http://jsonmoon.jsapp.us/], but with Access-Control-Origin response header</li>
</ol>
<div id="output"></div>

CSS

li {font-size: 22px; margin-bottom: 10px;}
div {font-size: 36px;}

JavaScript

document.getElementById('header').innerHTML = 'Origin: '+location.protocol+'//'+location.host;

window.getFullName = function(data){
    document.getElementById('output').innerHTML = 'JSONP data received. First name: '+data.firstName;
};

var links = document.getElementsByTagName('a');
for (var i=0;i<links.length;i++) {
    (function(link){
        link.onclick = function(){
            var type = this.getAttribute('data-ajax-type') || 'GET';
            if (type === 'JSONP') {
                var first = document.getElementsByTagName('script')[0];
                var jsonp = document.createElement('script');
                jsonp.src = this.href;
                first.parentNode.insertBefore(jsonp, first);
            } else {
                var xhr = new XMLHttpRequest();
                xhr.open(type, this.href, true);
                xhr.onreadystatechange = function(){
                    if (xhr.readyState === 4) {
                       var response = 'AJAX error!';
                       if (xhr.status === 200) {
                           response = 'AJAX data received:<br/><pre>' + xhr.responseText + '</pre>';
                       }
                       document.getElementById('output').innerHTML = response;
                    }
                };
                if (type === 'POST') {
                    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                    xhr.send('html=This%20is%20coming%20from%20AJAX.');
                } else {
                    xhr.send();
                }
            }
            document.getElementById('output').innerHTML = 'Loading ' + this.innerHTML;
            return false;
        };
    })(links[i]);
}