Introduction:

Here we will discuss how we can retrieve list items from SharePoint list using JSOM (JavaScript Object Model) in SharePoint Online Office 365 sites. The same code also works for SharePoint 2016 as well as SharePoint 2013.

In this particular example, let us create a SharePoint online list which has columns like:
  • Title
  • FirstName
  • LastName
And in that list there were few records inside it. The out of box list looks like below:



Here we will show try to retrieve this list data by using JSOM.

Here let us put our JSOM code inside a script editor web part which we will add inside a web part page.

JSOM Code:

Below is the full code:
 
<div id="divListItems"></div>
 
<script>
 
$(function () {
 
    ExecuteOrDelayUntilScriptLoaded(retrieveListItems, "sp.js");
 
});
 
function retrieveListItems() {
 
    var clientContext = new SP.ClientContext();
 
    var oList = clientContext.get_web().get_lists().getByTitle('Employees');
 
    var camlQuery = new SP.CamlQuery();
 
    this.collListItem = oList.getItems(camlQuery);
 
    clientContext.load(collListItem);
 
    clientContext.executeQueryAsync(
 
    Function.createDelegate(this, this.onQuerySucceeded),
 
    Function.createDelegate(this, this.onQueryFailed)
 
    );
 
}
 
function onQuerySucceeded(sender, args) {
 
    var listItemInfo = '';
 
    var listItemEnumerator = collListItem.getEnumerator();
 
    while (listItemEnumerator.moveNext()) {
 
        var oListItem = listItemEnumerator.get_current();
 
        listItemInfo += '<strong>ID: </strong> ' + oListItem.get_id() +
 
        ' <strong>Title:</strong> ' + oListItem.get_item('Title') +
 
        ' <strong>FirstName:</strong> ' + oListItem.get_item('FirstName') +
 
        ' <strong>LastName:</strong> ' + oListItem.get_item('LastName') +
 
        '<br />';
 
    }
 
    $("#divListItems").html(listItemInfo);
 
}
 
function onQueryFailed(sender, args) {
 
    alert('Request failed. ' + args.get_message() +
 
    '\n' + args.get_stackTrace());
 
}
 
</script>
If you save the code and refresh the page you can see the list items like below:



Here we have passed an empty CAML query.
var camlQuery = new SP.CamlQuery();
 
this.collListItem = oList.getItems(camlQuery);
But if you want to retrieve items based on certain filter conditions then you can write the CAML query and pass it like below:
var camlQuery = new SP.CamlQuery();
 
camlQuery.set_viewXml(
 
'<View><Query><Where><Geq><FieldRef Name=\'ID\'/>' +
 
'<Value Type=\'Number\'>2</Value></Geq></Where></Query>' +
 
'<RowLimit>10</RowLimit></View>'
 
);
 
this.collListItem = oList.getItems(camlQuery);
The above query will return results where the ID value greater than or equal to 2.

References:

If you want to learn about Microsoft Flow and Rest API, you can follow below articles.

Conclusion:

Here we have discussed how we can retrieve list items using JavaScript Object Model in SharePoint 2013.