Making cross domain requests in SharePoint hosted apps

Step I: First of all we need to capture the hosturl and appurl from the query string of the app url.

hostweburl =
decodeURIComponent(
getQueryStringParameter(“SPHostUrl”)
);
appweburl =
decodeURIComponent(
getQueryStringParameter(“SPAppWebUrl”)
);

//QueryString function

function getQueryStringParameter(paramToRetrieve) {
var params =
document.URL.split(“?”)[1].split(“&”);
var strParams = “”;
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split(“=”);
if (singleParam[0] == paramToRetrieve)
return singleParam[1];
}
}

Step II: Then we need to load the js file SP.RequestExecutor.js

var scriptbase = hostweburl + “/_layouts/15/”;

// Load the js files and continue to the successHandler
$.getScript(scriptbase + “SP.RequestExecutor.js”, makeCall);

makeCall is a success handler

Step III: Define makeCall

function makeCall() {
// executor: The RequestExecutor object
// Initialize the RequestExecutor with the app web URL.
var executor = new SP.RequestExecutor(appweburl);

// Issue the call against the app web.
// The response formats the data in the JSON format.
// The functions successHandler and errorHandler attend the
// sucess and error events respectively.
executor.executeAsync(
{
url:appweburl+”/_api/SP.AppContextSite(@t)/projectserver/projects?@t='”+hostweburl+”‘”,
method: “GET”,
headers: { “Accept”: “application/json; odata=verbose” },
success: successHandler,
error: errorHandler
}
);
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s