Thursday 31 March 2016

AJAX & JSON


AJAX JSON Example:

  • We can get JSON data by AJAX code. AJAX provides facility to get response asynchronously. It doesn't reload the page and saves bandwidth.

AJAX JSON Example:

Let's see a simple example of getting JSON data using AJAX code.
  1. <html> 
  2. <head> 
  3. <meta content="text/html; charset=utf-8"> 
  4. <title>AJAX JSON by Javatpoint</title> 
  5. <script type="application/javascript"> 
  6. function load() 
  7. var url = "http://date.jsontest.com/";//use any url that have json data 
  8. var request; 

  9. if(window.XMLHttpRequest){ 
  10. request=new XMLHttpRequest();//for Chrome, mozilla etc 
  11. else if(window.ActiveXObject){ 
  12. request=new ActiveXObject("Microsoft.XMLHTTP");//for IE only 
  13. request.onreadystatechange = function(){ 
  14. if (request.readyState == 4 ) 
  15. var jsonObj = JSON.parse(request.responseText);//JSON.parse() returns JSON object 
  16. document.getElementById("date").innerHTML = jsonObj.date; 
  17. document.getElementById("time").innerHTML = jsonObj.time; 
  18. request.open("GET", url, true); 
  19. request.send(); 
  20. </script> 
  21. </head> 
  22. <body> 
  23. Date: <span id="date"></span><br/> 
  24. Time: <span id="time"></span><br/> 
  25. <button type="button" onclick="load()">Load Information</button> 
  26. </body> 
  27. </html> 

Output:

Date: Time: Load Information