Wednesday, 23 July 2014

Read list data using Client Object model (ECMA Script)

Read list data using Client Object model (ECMA Script) :-

Pre-requisite:-
1.Create list named "Announcements" using "Announcements" list template.
2.Make some announcement entries inside that list.
3.Create a js file named "AnnouncementData.js" and copy paste the code given below, then upload the same in to "Site Assets" library.
4.Create an application page and add "Content Editor" webpart, edit the webpart and in properties section under "links" add the link of "AnnouncementData.js" and save page.

Output:-
An alert message will appear with list of all entries in "Announcements" list.

Note: The announcement list and webpart should exists in same site.

Source Code :-

<SharePoint:ScriptLink Name="SP.js" runat="server" OnDemand="true"
    Localizable="false" />
<SharePoint:FormDigest runat="server" />

<script type="text/javascript">

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) {

    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('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>

No comments:

Post a Comment