Monday, February 24, 2014

I've been enjoying using the JavaScript CSOM (Client Side Object Model) in SharePoint 2013 lately.  Here's some basic JavaScript for querying SharePoint list data.

//ensure loading of the sp.js file
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', spReady);

// The spReady() Function is the callback function
function spReady() {
// Create an instance of the current context.
// Get context based on current site -- this way you won't have to hardcode the url for the current site
    var clientContext = new SP.ClientContext.get_current();

    myList = clientContext.get_web().get_lists().getByTitle('<LISTNAME>');

//CAML Query to get all list items from the default list view
    var query = SP.CamlQuery.createAllItemsQuery();
// Get all of the list items based on the query
    spListItems = myList.getItems(query);

//Load the list items
    clientContext.load(spListItems);
        clientContext.executeQueryAsync(onLoadSuccess, onLoadFail);
}


function onLoadSuccess()
{
 var spListEnumerator = spListItems.getEnumerator();
        var item;
        var fieldvalue;

//Enumerate through each listItem
        while (spListEnumerator.moveNext())  {
            item = spListEnumerator.get_current();
//Get the field value in the current list item and display it as an alert.
            fieldvalue= item.get_item('<FIELDNAME>');
            alert(fieldvalue + " is the value of your requested SharePoint field!");
        }
}

No comments:

Post a Comment