JSON HTTP REQUEST

Click Here

JSON is often used to collect data from a web service and display the recovered data to a web page.

Example JSON HTTP REQUEST

If we have the following file "data.txt" in our server

File "data.json"

[ {"firstName":"Adam", "lastName":"Smith"}, {"firstName":"Anne", "lastName":"Davis"}, {"firstName":"Bruce", "lastName":"Harris"}, {"firstName":"David", "lastName":"Lee"} ]

HTML file that contains the JSON data for previous file and displays its data on the same HTML page.

HTML page "result.html"

<!DOCTYPE html> <html> <body> <div id="divdata"></div> <script> var xmlhttp = new XMLHttpRequest(); var url = "data.json"; function myTransform(arr) { var out = ""; var i; for(i = 0; i < arr.length; i++) { out += arr[i].firstName + arr[i].lastName + '<br/>'; } document.getElementById("divdata").innerHTML = out; } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var myData = JSON.parse(xmlhttp.responseText); myTransform(myData); } } xmlhttp.open("GET", url, true); xmlhttp.send(); </script> </body> </html>

The result of executing the above website "result.html" in the web browser will be:

Adam Smith Anne Davis Bruce Harris David Lee

Click Here