Pages

Wednesday, April 16, 2014

Get Site URL in Javascript

This post is more like a note of remembrance.I have been playing with Angular lately (I am not a expert just starting to explore). Thanks to my colleague Javed for his help. I was trying to create a web part to read information from the SharePoint site. I was faced with problem when trying to combine the CSOM with AngularJS. This could just be my poor Angular skills causing. But all i was trying to do was get the URL so I can do a GET using $http. I think the problem was in ExecuteQueryAsync.While trying to investigate I stumbled upon Nik Patel's article talking about getting site collection URL form.

Since we are using more and more javascript and client side development i think this would be a useful information to share.

_spPageContextInfo object is available by default in all SharePoint webpart pages and hence it becomes simple to get the URL as opposed to writing a lot of code to get a site collection URL. Though the returned URL is server relative we could easily form the full URL which can then be used in $http.get() in my case

here is how i used it

var url = window.location.protocol + "//" + window.location.host + _spPageContextInfo.siteServerRelativeUrl; 


// Form the full URL for $hhtp get
url = url + "_api/web/lists/GetByTitle('News')/items"


//Call Http Get
$http.get(url);

No comments:

Post a Comment