Pages

Tuesday, June 25, 2013

How to read data from a JSON file using jQuery (getJSON() method)

Here is the example how to read a simple JSON file data using jQuery getJSON() method,

Sample JSON file structure, 

{
"news1": "This is a first sample news feed",
"news2": "This is a second sample news feed",
"news3": "This is a third sample news feed"
}
this file you can store as .js or .json extension or even .txt (for this example, I store it as .js extension in script folder)

HTML 
<ul>
  <li><div id="news1" style="height:100px;width:auto"></div> </li>
  <li><div id="news2" style="height:100px;width:auto"></div></li>
  <li><div id="news3" style="height:100px;width:auto"></div> </li>
</ul>
jQuery
<script type="text/javascript">
 $(document).ready(
  function() {
      $.getJSON('script/news1.js', function(jd) {
   $('#news1').append('<p>' + jd.news1 + '</p>');
   $('#news2').append('<p>' + jd.news2 + '</p>');
   $('#news3').append('<p>' + jd.news3 + '</p>');  
   });  
 });
</script> 

No comments:

Post a Comment