Friday, 25 September 2015

AJAX JSON Example

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. {  
  8.    var url = "http://date.jsontest.com/";//use any url that have json data  
  9.    var request;  
  10.   
  11.    if(window.XMLHttpRequest){    
  12.     request=new XMLHttpRequest();//for Chrome, mozilla etc  
  13.    }    
  14.    else if(window.ActiveXObject){    
  15.     request=new ActiveXObject("Microsoft.XMLHTTP");//for IE only  
  16.    }    
  17.    request.onreadystatechange  = function(){  
  18.       if (request.readyState == 4  )  
  19.       {  
  20.         var jsonObj = JSON.parse(request.responseText);//JSON.parse() returns JSON object  
  21.         document.getElementById("date").innerHTML =  jsonObj.date;  
  22.         document.getElementById("time").innerHTML = jsonObj.time;  
  23.       }  
  24.    }  
  25.    request.open("GET", url, true);  
  26.    request.send();  
  27. }  
  28. </script>  
  29. </head>  
  30. <body>  
  31.   
  32. Date: <span id="date"></span><br/>  
  33. Time: <span id="time"></span><br/>  
  34.   
  35. <button type="button" onclick="load()">Load Information</button>  
  36. </body>  
  37. </html>  
Output:
Date: 
Time: 

No comments:

Post a Comment