//Global
variables
var context;
var hostweburl;
var appweburl;
var appContextSite;
var list;
var web;
//Code
included inside $( document ).ready() will only run once the page
//Document
Object Model (DOM) is ready for JavaScript code to execute
$(document).ready(function () {
//Ensures
that the specified file that contains the specified function is loaded and
//then
runs the specified callback function.
//SP.SOD.executeFunc('file name','function name',methos to
call post execution);
SP.SOD.executeFunc('sp.js', 'SP.ClientContext',
getUrl);
});
function getUrl() {
//Fetch
query string parameters
hostweburl = getQueryStringParameter("SPHostUrl");
appweburl = getQueryStringParameter("SPAppWebUrl");
//Decode
hostweburl =
decodeURIComponent(hostweburl);
appweburl =
decodeURIComponent(appweburl);
//Build
absolute path to the layouts root with the spHostUrl
var scriptbase = hostweburl + "/_layouts/15/";
//Before
you get SP.js, you have to get SP.Runtime.js
//Once
SP.js can be retrieved, it makes a call to the execOperation method.
//SP.ProxyWebRequestExecutorFactory
is located in sp.requestexecutor.js,
//which
also provides objects, methods, and properties for
//managing
Web request executors for client requests.
$.getScript(scriptbase + "SP.Runtime.js",
function () {
$.getScript(scriptbase + "SP.js",
function () { $.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest); }
);
}
);
}
function execCrossDomainRequest() {
context = new SP.ClientContext(appweburl);
var factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
context.set_webRequestExecutorFactory(factory);
appContextSite = new SP.AppContextSite(context,
hostweburl);
web = appContextSite.get_web();
context.load(web);
list = web.get_lists().getByTitle("Shared Documents");
context.load(list);
context.executeQueryAsync(onSuccess,
onFail);
}
function onSuccess() {
alert("List loaded Successfully");
}
// This
function is executed if the above call fails
function onFail(sender, args) {
alert( args.get_message());
}
//Generic
function to fetch query sting parameters
function getQueryStringParameter(paramToRetrieve)
{
var params =
document.URL.split("?")[1].split("&");
for (var i = 0; i < params.length; i = i + 1)
{
var singleParam = params[i].split("=");
if (singleParam[0] == paramToRetrieve)
return singleParam[1];
}
}