CustomCodes‎ > ‎

SharePoint Hosted app - Getting cross domain list data using REST

// Getting list data from cross domain using REST

'use strict';

var context = SP.ClientContext.get_current();

var user = context.get_web().get_currentUser();

var web = context.get_web();

var lists = web.get_lists();

var listItemCollection;

var hostweburl;

var appweburl;

function getQueryStringParameter(paramToRetrive) {

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] == paramToRetrive) return singleParam[1];

}

}

hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));

appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));

(function () {

$(document).ready(function () {

$.getScript(hostweburl + "/_layouts/15/SP.RequestExecutor.js",continueExecution);

});

// Function to call REST query.

function continueExecution() {

var executor;

//var viewXml = "<View Scope='RecursiveAll'><Query><OrderBy><FieldRef Name='Title' Ascending='False' /></OrderBy></Query></View>";

var listname = 'MyCountryList';

executor = new SP.RequestExecutor(appweburl);

executor.executeAsync(

{

url: appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('" + listname + "')/[email protected]='" + hostweburl + "/'",

method: "GET",

headers: { "Accept": "application/json; odata=verbose" },

success: successHandler,

error: errorHandler

}

);

}

// Function to handle the success event.

function successHandler(data) {

var innerData = "<div><span><b>Country</b></span>&nbsp;&nbsp;<span><b>Country Code</b></span></div>";

var jsonObject = JSON.parse(data.body);

var results = jsonObject.d.results;

for (var i = 0; i < results.length; i++) {

console.log(results[i].Title);

innerData = innerData + "<div><span>" + results[i].Title + "</span>&nbsp;&nbsp;<span>" + results[i].Code + "</span></div>"

}

$("#RestMethod").append(innerData);

}

// Function to handle the error event.

function errorHandler(data, errorCode, errorMessage) {

$("#RestMethod").append("Could not complete cross-domain call: " + errorMessage);

}

})();