Wednesday, June 9, 2010

Jquery - Reading Data from XML or JSON data types

(1) Upload files in document library upload json.json and Topics.xml in the root level site.


(2) JSON.JSON:

{
    topics:{
          topic:[
               'Select Topic',
               '1 - Testing Json!',
               '2 - Analysis Statement',
                 '3 - Another element',
              ]
         }
}


(3) TOPICS.XML:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<Topics>
        <Topic>Select Topic</Topic>
        <Topic>1 - Testing Json!</Topic>
        <Topic>2 - Analysis Statement</Topic>
         <Topic>3 - Another element</Topic>
</Topics>



(4) Jquery would be:


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function()

{

     //Binding Json Data using Jquery
       $.getJSON('http://YourServer/DocumentLibrary/json.json', function(data)
      {

         var numItems = data.topics.topic.length // To Count the number of elements in particular node
        //Iterate through all the elements in that particular node
          for(i=1;i<numItems;i++)
         {
            $("<option value='SELECT'>" + data.topics.topic[i] + "</option>").appendTo("#ddlTopic");
           //Binding it to another dropdown with id ddlTopic
          }
        });



//Binding XML data using Jquery

      $.ajax(
      {

         type:"GET",
         url:"http://YourServer/DocumentLibrary/Topics.xml",
         dataType:"xml",
         success:function(xml){

          $(xml).find('Topic').each(function(){
          var topic = $(this).text();
           //Binding it to another dropdown with id ddTopic

            $("<option value='SELECT'>" + topic + "</option>").appendTo("#ddTopic");
      
              }); // end each() loop
          } // end success
  }); // end ajax()

});//end ready()

</script>

No comments: