'use strict';
ExecuteOrDelayUntilScriptLoaded(initializePage, "sp.js");
function initializePage() { var context, appContext, hostWeb, user, lists, listItemCollection, projectList;
// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
$(document).ready(function () {
// Get hostweb and appweb string values
var appWebUrl = window.location.protocol + "//" + window.location.hostname + _spPageContextInfo.webServerRelativeUrl;
var hostUrl = _spPageContextInfo.siteAbsoluteUrl;
// Create and access objects
context = new SP.ClientContext(appWebUrl);
// Host web data access
appContext = new SP.AppContextSite(context, hostUrl);
hostWeb = appContext.get_web();
lists = hostWeb.get_lists();
projectList = lists.getByTitle('Projects');
// Generate a CamlQuery
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml(
'<View><Query><Where><Geq><FieldRef Name=\'ID\'/>' +
'<Value Type=\'Number\'>1</Value></Geq></Where></Query><RowLimit>10</RowLimit></View>'
);
// Get the items using the query
listItemCollection = projectList.getItems(camlQuery);
// Load the object to browser
context.load(listItemCollection);
context.executeQueryAsync(
Function.createDelegate(this, listSuccess),
Function.createDelegate(this, listFail)
);
});
function listSuccess() {
alert('Success');
}
function listFail(sender, args) {
alert('Request failed. ' + args.get_message() +
'\n' + args.get_stackTrace());
}
}
The browser loads the object but the collection seems to be empty. When i test this code on the success handler
function listSuccess() {
alert(listItemCollection.get_itemCount());
}
This will return the expected number of items. But when I try this code
firstItem = listItemCollection.getById(1);
This will run the error handler callback Finally, when I iterate using the enumerator
alert(itemEnumerator.moveNext());
It will display a false meaning there are no items on the loaded collection. When I replace it with local app web list items and not host web list items, I can access them without any issues. One more thing, the program is located in App testing list for a development site so the url contains some random codes like https://{myhostname}-{randomcodehere}.sharepoint.com/sites/bm while the list items I am trying to access is located on the https://{myhostname}.sharepoint.com/sites/bm.