JSON Http Request
A common use of JSON is to read data from a web server, and display the data in a web page.
This chapter will teach you, in 4 easy steps, how to read JSON data, using XMLHttp.
JSON Example
This example reads a menu from myTutorials.txt, and displays the menu in a web page:
JSON Example
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "myTutorials.txt";
xmlhttp.onreadystatechange = function()
{
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>
Try it yourself »
Example Explained
1: Create an array of objects.
Use an array literal to declare an array of objects.
Give each object two properties: display and url.
Name the array myArray:
myArray
var myArray = [
{
"display": "JavaScript Tutorial",
"url": "https://www.noidatut.com/js/default.asp"
},
{
"display": "HTML Tutorial",
"url": "https://www.noidatut.com/html/default.asp"
},
{
"display": "CSS Tutorial",
"url": "https://www.noidatut.com/css/default.asp"
}
]
2: Create a JavaScript function to display the array.
Create a function myFunction() that loops the array objects, and display the content as HTML links:
myFunction()
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;
}
Call myFunction() with myArray as argument:
3: Create a text file
Put the array literal in a file named myTutorials.txt:
myTutorials.txt
[
{
"display": "JavaScript Tutorial",
"url": "https://www.noidatut.com/js/default.asp"
},
{
"display": "HTML Tutorial",
"url": "https://www.noidatut.com/html/default.asp"
},
{
"display": "CSS Tutorial",
"url": "https://www.noidatut.com/css/default.asp"
}
]
Look at the file »
4: Read the text file with an XMLHttpRequest
Write an XMLHttpRequest to read the text file, and use myFunction() to display the array:
XMLHttpRequest
var xmlhttp = new XMLHttpRequest();
var url = "myTutorials.txt";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 &&
xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET",
url, true);
xmlhttp.send();
Try it yourself »