Cheap VPS & Xen Server


Residential Proxy Network - Hourly & Monthly Packages

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

Output:

Date: 
Time: 

Comments

comments