Saturday, January 14, 2017

JSON (JavaScript Object Notation) HTTP Request by Ajax to Show Data on Webpage

First,We create one .Txt file which contains names of different countries.

Country.txt File: 
  1. [  
  2.     {  
  3.         "display""India",  
  4.     },   
  5.     {  
  6.         "display""China",  
  7.     },   
  8.     {  
  9.         "display""USA",  
  10.     },   
  11.     {  
  12.         "display""UK",  
  13.     },   
  14.     {  
  15.         "display""Canada",  
  16.     },   
  17.     {  
  18.         "display""Japan",  
  19.     },   
  20.     {  
  21.         "display""Russia",  
  22.     },   
  23. ]  
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  
  1. <!DOCTYPE html>  
  2. <html>  
  3. <body>  
  4. <div id="maindiv"></div>  
  5. <script>  
  6. var xmlhttp = new XMLHttpRequest();  
  7. var url = "Country.txt";  
  8. xmlhttp.onreadystatechange = function()  
  9. {  
  10.    if (xmlhttp.readyState == 4 && xmlhttp.status == 200)  
  11.    {  
  12.          var myarray = JSON.parse(xmlhttp.responseText);  
  13.          fetchData(myarray);  
  14.    }  
  15. }  
  16. xmlhttp.open("GET", url, true);  
  17. xmlhttp.send();  
  18. function fetchData(arr)  
  19. {  
  20.          var out = "";  
  21.          var i;  
  22.           for(i = 0; i < arr.length; i++)  
  23.          {  
  24.                out += arr[i].display + '<br>';  
  25.          }  
  26.          document.getElementById("maindiv").innerHTML = out;  
  27. }  
  28. </script>  
  29. </body>  
  30. </html>  
After completing all these steps, you will get following output.

India
China
USA
UK
Canada
Japan
Russia 
Enjoy Coding...!!!

No comments:

Post a Comment