Is there a way to get the list of sites in the current site collection into jQuery as an array or other data structure? Thanks.
1 Answer
You can use the ECMA Script Client Object Model:
ExecuteOrDelayUntilScriptLoaded(loadWebs, "sp.js");
function loadWebs() {
var clientContext = new SP.ClientContext.get_current();
this.webs = clientContext.get_web().get_webs();
clientContext.load(this.webs);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onWebsLoaded), Function.createDelegate(this, this.onQueryFailed));
}
function onQueryFailed(sender, args) {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}
function onWebsLoaded(sender, args) {
for (var i = 0; i < this.webs.get_count(); i++) {
alert(this.webs.itemAt(i).get_title());
}
}
-
1Thanks, Vardhaman. Where did you get the syntax for the Client Object Model? Is there documentation on SharePoint/JavaScript? Thanks.– Alex CSep 4, 2011 at 5:47
-
3Here is the MSDN link for the classes: msdn.microsoft.com/en-us/library/ee557057.aspx also check out the following MSDN article series: blogs.msdn.com/b/sharepointdev/archive/2011/07/13/… Sep 4, 2011 at 5:50
-
It's giving me a JavaScript error:
SP.ClientContext is undefined
. I just noticed that the JS file in my page layout loads before the required SP.js files are loaded; any way to fix this?– Alex CSep 4, 2011 at 5:53 -
1I have edited the original code. see the ExecuteOrDelayUntilScriptLoaded function. Sep 4, 2011 at 5:56
-
Thanks, Vardhaman. It worked like a charm once I added the
ExecuteOrDelayUntilScriptLoaded()
function. Also, I placed it inside the jQuery$(document).ready()
function. By the way, if we run this from a site, it seems to only return that site's title; does it need to be run from a master page for the entire site collection to return all sites?– Alex CSep 4, 2011 at 6:02