10 February 2014

Retrieving JSON objects using AJAX

I have a simple code here that I use to read JSON data.

function loadJSON() {
   
    "use strict";

    var xhr = false;
   
    if (window.XMLHttpRequest) {
       
        xhr = new XMLHttpRequest();
       
    } else {
       
        xhr = new ActiveXObject('Microsoft.XMLHTTP');
       
    }   
   
    if (xhr) {
   
    xhr.open("GET", "data.json", true);
    xhr.send(null);   
    xhr.onreadystatechange = getContents;
   
    } else {   
   
    document.getElementById("myDiv").innerHTML = "Sorry. Unable to process your request. Try again later.";
   
    }
   
    function getContents() {
   
        if (xhr.readyState == 4){
       
            if (xhr.status == 200 || window.location.href.indexOf("http") == -1) {
           
                //To retrieve as a JavaScript object
               
                var jsonData = eval("("+xhr.responseText+")");                
                var getData = jsonData.items;       
               
                var output = '';
                for (var i = 0; i < getData.length; i++) {
                    output +=    '<ul>';
                    output +=    '<li>';
                    output +=    '<a href="' + getData[i].website + '">';
                    output +=    getData[i].name + '</a>';
                    output += '</li>';
                    output += '</ul>';
                }
               
                output += '</ul>';               
                document.getElementById("myDiv").innerHTML = output;               
            }                   
        }       
    }
}

No comments:

Post a Comment