7

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 1

7

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());

       }    
    }
5
  • 1
    Thanks, Vardhaman. Where did you get the syntax for the Client Object Model? Is there documentation on SharePoint/JavaScript? Thanks.
    – Alex C
    Sep 4, 2011 at 5:47
  • 3
    Here 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 C
    Sep 4, 2011 at 5:53
  • 1
    I 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 C
    Sep 4, 2011 at 6:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.