2

I have tried the below code for getting all sub-sites using rest...

<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>

<script>

ExecuteOrDelayUntilScriptLoaded(RetriveSites,"sp.js");

function RetriveSites()
{
$.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/SP.AppContextSite(@target)/web/webs?$select=Title,ServerRelativeUrl&@target=",
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        },
        success: function (data) {
alert("sds");
            console.log(data.d.results);
        },
        error: function (error) {
            alert(JSON.stringify(error));
        }
    });
}



</script>

I am not able to get sub-sites ,it is just showing an alert with some random data. Please help me with the code.

  • The alert with random data is actually error log I assume, as you have an alert in your error callback. Please post the error details – Unnie Nov 9 '15 at 16:31
  • yes it is going to the error. I think the problem is with the url I have given, – KumarV Nov 9 '15 at 16:32
  • Also the SP.AppContextSite(@target) is used for cross domain calls. Where are you calling this javascript from? Are you trying to get subsites in another domain? – Unnie Nov 9 '15 at 16:34
  • no, in the same domain, please help me with the url – KumarV Nov 9 '15 at 16:34
7

You have to use /_api/SP.AppContextSite(@target)/web/webs only when you are making any cross domain calls like for eg: inside a SharePoint hosted app or Provider hosted app etc. To get the sub sites under the current site use below format for url.

$.ajax({
  url: "http://<site url>/_api/web/webs",
  type: "GET",
  headers: { "accept": "application/json;odata=verbose" },
  success: function (data) {
           console.log(data.d.results);
    },
  error: function (error) {
        alert(JSON.stringify(error));
    }
});
  • Its working now, now I need to display all sub site names on a site. data.d.result shows only "object object" – KumarV Nov 9 '15 at 16:52
  • That's because it is an object. To view it in the console use console.log("%O", data.d.results); – James Love Nov 11 '15 at 9:40
0

http://<site url>/_api/web/webs

This call is not enough, unless if all users are allowed to access a subsite. It will throw a System.UnathorizedAcces exception if a subsite is not available for access to a certain user.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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