CSOM – Get site object using JavaScript

Working with CSOM using JavaScript is slight different in syntax, but the process involved with getting the objects required for coding is the same! You still need to use the context object, load the context object, and execute the query that will send the context object off to SharePoint to tell it what you want and have it returned back.

The syntax is slightly different and the context return object is used in a different way:

var ctx;

var web;

var lists;

$(onPageLoad);

function onPageLoad()

{

ExecuteOrDelayUntilScriptLoaded(LoadAll, “sp.js”);

}

function LoadAll()

{

ctx = SP.ClientContext.get_current();

web = ctx.get_web();

ctx.load(web);

ctx.load(web.get_currentUser());

lists = web.get_lists();

ctx.load(lists);

ctx.executeQueryAsync(doSomething, displayError);

}

function doSomething()

{

var siteTitle = web.get_title();

var siteId = web.get_id().toString();

var siteUrl = web.get_url();

var currentUser = web.get_currentUser().get_loginName();

}

function onError(sender, args)

{

alert(JSON.stringify(args));

}

Advertisements