First,We create one .Txt file which contains names of different countries.
Country.txt File:
[
{
"display": "India",
},
{
"display": "China",
},
{
"display": "USA",
},
{
"display": "UK",
},
{
"display": "Canada",
},
{
"display": "Japan",
},
{
"display": "Russia",
},
]
In the second step, Reads the data from file and display it to the webpage. Use XMLHttpRequest to read the text file, and use fetchData () to display the array.JsonHttpXmlReqbyAjax.html
<!DOCTYPE html>
<html>
<body>
<div id="maindiv"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "Country.txt";
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var myarray = JSON.parse(xmlhttp.responseText);
fetchData(myarray);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function fetchData(arr)
{
var out = "";
var i;
for(i = 0; i < arr.length; i++)
{
out += arr[i].display + '<br>';
}
document.getElementById("maindiv").innerHTML = out;
}
</script>
</body>
</html>
After completing all these steps, you will get following output.India
China
USA
UK
Canada
Japan
Russia
Enjoy Coding...!!!
