WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

JSON Http Request


A normal utilization of JSON is to peruse information from a web server, also, show the information in a web page.

This section will show you, in 4 simple advances, how to peruse JSON information, utilizing XMLHttp.


JSON Example

This model peruses a menu from myTutorials.txt, and shows the menu in a web page:

JSON Example

<div id="id01"></div>

<script>
var xmlhttp = new XMLHttpRequest();
var url = "myTutorials.txt";

xmlhttp.onreadystatechange = work() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        var myArr = JSON.parse(xmlhttp.responseText);
        myFunction(myArr);
    }
};
xmlhttp.open("GET", url, true);
xmlhttp.send();

function myFunction(arr) {
    var out = "";
    var i;
    for(i = 0; I < arr.length; i++) {
        out += '<a href="' + arr[i].url + '">' +
        arr[i].display + '</a><br>';
    }
    document.getElementById("id01").innerHTML = out;
}
</script>

Example Explained

1: Create a variety of objects.

Use a array literal to pronounce a array of objects.

Give each item two properties: display and url.

Name the cluster myArray:

myArray

var myArray = [
{
"display": "JavaScript Tutorial",
"url": "http://www.welookups.com/js/default.html"
},
{
"display": "HTML Tutorial",
"url": "http://www.welookups.com/html/default.html"
},
{
"display": "CSS Tutorial",
"url": "http://www.welookups.com/css/default.html"
}
]

2: Create a JavaScript capacity to show the array. 

Create a capacity myFunction() that circles the exhibit objects, what's more, show the substance as HTML links:

myFunction()

work myFunction(arr) {
    var out = "";
    var i;
    for(i = 0; I < arr.length; i++) {
        out += '<a href="' + arr[i].url + '">' + arr[i].display + '</a><br>';
    }
    document.getElementById("id01").innerHTML = out;
}

Call myFunction() with myArray as argument:

Example

myFunction(myArray);

3: Create a content file

Put the array literal in a record named myTutorials.txt:

myTutorials.txt

[
{
"display": "JavaScript Tutorial",
"url": "http://www.welookups.com/js/default.html"
},
{
"display": "HTML Tutorial",
"url": "http://www.welookups.com/html/default.html"
},
{
"display": "CSS Tutorial",
"url": "http://www.welookups.com/css/default.html"
}
]

4: Read the content record with a XMLHttpRequest

Write a XMLHttpRequest to peruse the content record, and use myFunction() to show the array:

XMLHttpRequest

var xmlhttp = new XMLHttpRequest();
var url = "myTutorials.txt";

xmlhttp.onreadystatechange = work() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    var myArr = JSON.parse(xmlhttp.responseText);
    myFunction(myArr);
    }
};

xmlhttp.open("GET", url, true);
xmlhttp.send();