Skip to content

Instantly share code, notes, and snippets.

@spdustin
Last active July 18, 2016 23:30
Show Gist options
  • Save spdustin/ba064af1fe0709b56c53de75371c8ff8 to your computer and use it in GitHub Desktop.
Save spdustin/ba064af1fe0709b56c53de75371c8ff8 to your computer and use it in GitHub Desktop.
Sample (and verbose) boilerplate for accessing SharePoint list data
/**
* Note: This example is _purposefully verbose_, for ease of reading.
*
* In an ideal world, your generic function would return the list items, and
* another function would actually be enqueued in the SOD call that calls
* (in IE9) just Array.forEach() through them for one-by-one processing,
* for example. Hope this helps!
*/
// This function will console.log items from the list you specify in the
// variable "list"
function doSomethingWithListItems() {
// Your list goes here by name
var list = 'Announcements';
// The root path to the current site is...
var webRoot = _spPageContextInfo.webServerRelativeUrl;
// This gets the odata endpoint for the current site and the list you need
var listSvc = webRoot + '_vti_bin/listdata.svc/' + list;
// Who needs jQuery? This works in IE8+
var request = new XMLHttpRequest();
// Prepare to make the request
request.open('GET', listSvc, true);
// This is how we do it... when the XMLHttpRequest tells us something can be done
request.onreadystatechange = function() {
// Are we there yet?
if (this.readyState === 4) {
// Did we get there OK?
if (this.status >= 200 && this.status < 400) {
// Holla! We have data
var responseData = JSON.parse(this.responseText);
// Just the list items, please...
var listItems = responseData.d.results;
// Do stuff with the listItems here
for (var idx = 0; idx < listItems.length; idx++) {
// Ideally something more than logging them to the console
console.log(listItems[idx]);
}
} else {
// Woe upon your code, something is amiss
console.log('Error getting', list, '-', this.status, this.statusText);
}
}
};
// Let's actually do it; send the XMLHttpRequest!
request.send();
}
// Okay, let's be absolutely sure that "secret" global _spPageContextInfo is
// available for us to use before we make our request, and that other
// SP initialization stuff is done that might interfere with our function
ExecuteOrDelayUntilScriptLoaded(doSomethingWithListItems, "init.js");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment