Get Host site list items in SharePoint Hosted App.
Those who starts
working on Apps might face issues to read host site list items. In sharepoint
hosted APP using Rest API we able to query host site list items. The rest
url to get host site is almost similar to get list items but we need to specify
the app context and target. Make sure JQuery loaded before to execute the code
in app web parts.
'use strict';
var
HostUrl="";
var
AppUrl=="";
// load function
// Intialize
HostUrl, AppUrl from query strings.
// call get items
method
$(document).ready(function
() {
HostUrl=
GetQueryString("SPHostUrl"); //
Get Host Url from query string
AppUrl=
GetQueryString("SPAppWebUrl"); //
Get App Url from query string
getItems("DemoList"); //
get list items
});
//
function to get list items using Rest Api
function
getItems(listname) {
$.ajax({
url: AppUrl +
"/_api/SP.AppContextSite(@target)/web/lists/getbytitle('" + listname
+ "')/items?@target='" + HostUrl+"'",
data: "GET",
headers: {
"accept":
"application/json; odata=verbose"
},
success: function (data) {
// manipulate data
},
});
}
//
function to get query string from url
// split and traverse each query string
until identify
function GetQueryString(key) {
var params =
document.URL.split('?')[1].split('&');
for (var i = 0; i < params.length;
i++) {
var p =
decodeURIComponent(params[i]);
if (p.split('=')[0] == key) {
return p.split('=')[1];
}
}
}
Straight forward. Nice
ReplyDeleteGood to hear from you...
ReplyDelete