Thursday, July 25, 2013

Read List Items using Client Object Model JavaScript SharePoint 2010

Below script reads announcements items and shows in the alert box.

<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">

Add below script here or add a content editor webpart to your page and include the script

</asp:Content>

    
 <script type="text/javascript">

     ExecuteOrDelayUntilScriptLoaded(retrieveListItems, "sp.js");
     // jQuery(document).ready(function(){
     //        ExecuteOrDelayUntilScriptLoaded(retrieveListItems, "sp.js");
     //   });

     function retrieveListItems() {

         var clientContext = new SP.ClientContext.get_current();
         var oList = clientContext.get_web().get_lists().getByTitle('Announcements');

         var camlQuery = new SP.CamlQuery();
         camlQuery.set_viewXml('<View><Query><Where><Geq><FieldRef Name=\'ID\'/>' +
        '<Value Type=\'Number\'>1</Value></Geq></Where></Query><RowLimit>10</RowLimit></View>');
         this.collListItem = oList.getItems(camlQuery);

         clientContext.load(collListItem);

         clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));

     }

     function onQuerySucceeded(sender, args) {
         alert('sucess');
         var listItemInfo = '';

         var listItemEnumerator = collListItem.getEnumerator();

         while (listItemEnumerator.moveNext()) {
             var oListItem = listItemEnumerator.get_current();
             listItemInfo += '\nID: ' + oListItem.get_id() +
            '\nTitle: ' + oListItem.get_item('Title') +
            '\nBody: ' + oListItem.get_item('Body');
         }

         alert(listItemInfo.toString());
     }

     function onQueryFailed(sender, args) {

         alert('fail');
         alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
     }</script>





No comments:

Post a Comment

Followers