Tuesday, April 11, 2017

How to use JSOM to get the list of documents from SharePoint Document Library

there are so many way to perform a task that iterating the list of document inside the docoumnt library. we can do either with CSOM with C# or JSOM with Javascript.

Here i will show a very simple way to execute this task.

<script type="text/javascript">
function getDocuments(title) {
   var context = SP.ClientContext.get_current();
   var web = context.get_web();
   var docLibrary = web.get_lists().getByTitle();
//here we can use SP.CamlQuery to filter the list if we need to
//load the the document by certain criteria.
   var items = docLibrary.getItems(SP.CamlQuery.createAllItemsQuery());
   context.load(items,"Include(File)");
   context.executeQueryAsync(
     function () {
        if (items.get_count() > 0) {
            var e = items.getEnumerator();
            while (e.moveNext()) {
                var item = e.get_current();
                var file = item.get_file();
                var title = file.get_title();
                var name = file.get_name();
                console.log(title + "      " + name );
            }
        }
     },
     function (sender, args) {
        console.log("Error in Loading Documents: " + args.get_message());
     }
     );
}



// We will use the delegate function to allow the ExecuteOrDelayUntilScriptLoaded function
//run a function with paramenters and this fucntion will ensure that sp.js is sucessfully loaded
//before running getDocuments function.

$(document).ready(function () {
   ExecuteOrDelayUntilScriptLoaded(function() {getDocuments("Sales Documents")}, "sp.js");
});
</script>


For more information please visit the following link from MSDN

How to: Retrieve List Items Using JavaScript

No comments:

Post a Comment