var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
var web = context.get_web();
var lists = web.get_lists();
Listing 13-3: Define variables
2. In the main function(), after getUserNames();, add following code:
$("#getLists").click(function (event) {
showLists();
event.preventDefault();
});
Listing 13-4: Call ShowLists()
3. Add following functions after the main function():
function showLists()
{
lists = web.get_lists();
context.load(lists);
context.executeQueryAsync(onshowListsSuccess,onshowListsFail);
}
function onshowListsSuccess(sender, arg)
{
var lstEnum = lists.getEnumerator();
var strLists ='';
while(lstEnum.moveNext())
{
if (strLists==='')
strLists = lstEnum.get_current().get_title();
else
strLists += ', ' + lstEnum.get_current().get_title();
}
alert('Total # of lists is: ' + lists.get_count() + ' and List names are: ' + strLists);
}
function onshowListsFail(sender, args)
{
alert('Error occurred! Message: ' + args.get_message());
}
Listing 13-5: Add functions
executeQueryAsync() executes the current pending request asynchronously on the server by using the client side object model (CSOM). It accepts two parameters. succeededCallback is a function or a delegate of the method to call if the request executes successfully. failedCallback is a function or a delegate of the method to call if the request fails to execute. When a function executes asynchronously, script continues to run without waiting for the server to respond.
lists.get_count() returns the count of lists in the site. lstEnum.get_current().get_title() where lstEnum is the list enumerator returns the title of each list. We store list titles in a string and then display the string when the list title reading loop has ended.
4. Click Run Project (play icon) button to run the app. App will run and display Get Lists button. Click it to see the result. An alert message will be displayed with the number of lists and their names.
Alert message showing list count and titles |
No comments:
Post a Comment