Foros‎ > ‎Sharepoint‎ > ‎

Getting SharePoint List items with SharePoint’s REST API in JavaScript

publicado a la‎(s)‎ 28 jul. 2015 8:19 por Ignacio Gonzalez
BY GREG OSTROWSKI ON 10-22-2014 2:07 PM

In my past few SharePoint projects, I’ve been tasked with creating custom JavaScript web parts to display and/or edit list items. When I first had to figure this out, it wasn’t particularly straight forward and basic. While SharePoint gives multiple options on how to use their lists, I was looking for the right one for me. SharePoint 2013 was able to provide me with  a REST API I could call with jQuery ajax requests, and this was exactly what I wanted. 

In my example, I'm accessing a generic task list and outputting the results into a table. I filter my query to grab tasks only assigned to the currently logged in user and only tasks that have not yet been completed. SharePoint's REST API lets us add these filters in our request. The results are given to us as a JSON object, which we can then loop through and insert into a table. I also used a modular pattern to structure my code.

On initialization, we need to know who the user is so we can get them their personalized tasks. SharePoint has some code for us that does exactly this.

Once we know our user's ID, we can generate our REST request. _spPageContextInfo is a SharePoint object that gives us useful information about the page and site we're on, including the base URL of our site.

After successfully getting our list information, we just need to loop through our data, put it in a table, and then insert into our predefined container element. jQuery helps make this an easy process.

Look at my follow up blog to learn how to use this same method to update your items and save the updated list information with REST API calls.

/* Requires jQuery */

var Module = {} || Module;

Module.GetTasks = (function () {
    var pub = {},
        _userId,            //userID of current user
        _tasks = [],        //List of our tasks
        _options = {
            listName: "Tasks",                  //Name of list we want
            container: "#TaskListContainer",    //id of html element we're rendering our list of tasks in
        };

    //Module Initializer
    pub.init = function () {
        var clientContext = new SP.ClientContext.get_current();
        _userId = clientContext.get_web().get_currentUser();
        clientContext.load(_userId);
        clientContext.executeQueryAsync(getUserInfo, _onQueryFailed);
       
    };


    //Once we have our userId, we make Asyncronous call to get our list defined by _options.listName
    function getUserInfo() {
        _userId = _userId.get_id();

        getSpecifiedList(_options.listName, _userId);
    }

    //Makes a REST Call to grab a specified List with items assigned to the userId. Items must not have a status of 'Completed'
    function getSpecifiedList(listName, userId) {
        var url = _spPageContextInfo.webAbsoluteUrl + "/_api/lists/getbytitle('" + listName + "')/items?$filter=(AssignedTo eq '" + userId + "') and (Status ne 'Completed')";
        $.ajax({
            url: url,
            type: "GET",
            headers: {
                "accept": "application/json;odata=verbose",
            },
            success: function (results) { createTaskView(results, listName); },
            error: function (error) { 
                console.log("Error in getting List: " + listName); 
                $(_options.container).html("Error retrieving your " + listName + ".");
            }
        });
    }

    //Upon Receiving Task List data, we set as our module's _task list .
    //We then iterate through each task and add to a table which we then insert into our container defined in _options.container
    function createTaskView(results, listName) {
        _tasks = results.d.results;

        var table = $("<table style='width: 100%;'>" +
                            "<tr>" +
                                "<th>Title</th>" +
                                "<th>Due Date</th>" +
                                "<th>Status</th>" +
                            "</tr>" +
                      "</table>");
        $.each(_tasks, function (index, task) {
            var tr = '<tr>' +
                       '<td>' + task.Title + '</td>' +
                       '<td>' + new Date(item.DueDate).toLocaleDateString() + '</td>' +
                       '<td>' + task.Status + '</td>' +
                    '</tr>';
            table.append(tr);
        });
        $(_options.container).html(table);
    }

    function _onQueryFailed(sender, args) {
        alert('Request failed. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
    }

    return pub;
}());

$(document).ready(function () {
    //must wait for SP scripts as we require them in our code
    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {
        Module.GetTasks.init();
    });
});
Comments