Working with the JavaScript client object model
The JavaScript client object model is really only a viable choice in
SharePoint-hosted apps for which C# code is not allowed and the pages
have an associated SharePoint context. The SharePoint 2013 app project
template for SharePoint-hosted apps provides some initial template code
to implement a welcome message. This code is a good place to see the
fundamentals of CSOM in action. Example 9 comes from the app project template for a SharePoint-hosted app.
Example 9. Visual Studio 2012 app project template code
var context;
var web;
var user;
$(document).ready(function () {
context = SP.ClientContext.get_current();
web = context.get_web();
getUserName();
});
function getUserName() {
user = web.get_currentUser();
context.load(user);
context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
}
function onGetUserNameSuccess() {
$('#message').text('Hello ' + user.get_title());
}
function onGetUserNameFail(sender, args) {
alert('Failed to get user name. Error:' + args.get_message());
}
The code in Example 9 creates three variables in the global namespace named context, web, and user to reference objects needed globally. The context variable is used to setup the SharePoint context on the client side so that calls can be made back to the Client.svc endpoint; the web variable is used to reference the app web itself; and the user variable references the current app user.
Note
This template code violates the best practice of encapsulating code
in a separate namespace and using strict JavaScript. Therefore, it is
best to simply delete all of the template code when creating your own
apps.
To populate the variables, a call is made to the load method to specify that the scalar properties should be loaded, and then a call to the executeQueryAsync method is made to make an asynchronous call to the Client.svc endpoint. In the app project code, the round trip populates not only information about
the app web, but also information about the current user. Combining
operations in this way makes CSOM programming more efficient. Two
callback functions, which the template code names onGetUserNameSuccess and onGetUserNameFail,
are passed. The first callback function named is called if the round
trip completes without errors. The second callback function is called
if errors occur.
The JavaScript client object model supports both a load and loadQuery method. The loadQuery
method can be used to store a collection into a variable other than the
one referencing the desired collection. In either method, you can use
query strings to request that collections be included in the returned
results. Example 10
illustrates how to use the JavaScript client object model to return all
of the list titles in the app web along with the field names and
descriptions for each list.
Example 10. Returning collections by using JavaScript
"use strict";
var Wingtip = window.Wingtip || {}
Wingtip.Collections = function () {
//private members
var site,
listCollection,
getListCollection = function () {
var ctx = new SP.ClientContext.get_current();
site = ctx.get_web();
ctx.load(site);
listCollection = site.get_lists();
ctx.load(listCollection,
'Include(Title,Id,Fields.Include(Title,Description))');
ctx.executeQueryAsync(success, failure);
},
success = function () {
var html = [];
//List Information
html.push("<ul>");
var listEnumerator = listCollection.getEnumerator();
while (listEnumerator.moveNext()) {
//List Title
html.push("<li>");
html.push(listEnumerator.get_current().get_title());
html.push("<ul>");
//Field Names
var fieldEnumerator =
listEnumerator.get_current().get_fields().getEnumerator();
while (fieldEnumerator.moveNext()) {
html.push("<li>");
html.push(fieldEnumerator.get_current().get_title());
html.push("</li>");
}
html.push("</ul></li>");
}
html.push("</ul>");
//Show results
$("#displayDiv").html(html.join(''));
},
failure = function (sender, args) {
alert(args.get_message());
}
//public interface
return {
execute: getListCollection
}
}();
$(document).ready(function () {
Wingtip.Collections.execute();
});