Get list items by JavaScript CSOM

16/12/2015 04:07

getListItems function example how to get list items by using javascript client side object model (CSOM).

 

(function () {
    if (typeof MyJSNamespace == "object") {
        return;
    }
    window.MyJSNamespace = (function () {
        return {

            getListItems: function () {
                         
                    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {

                        var clientContext = SP.ClientContext.get_current();
                        var oList = clientContext.get_site().get_rootWeb().get_lists().getByTitle('MyListTitle');
                      
                        var camlQuery = new SP.CamlQuery();
                        camlQuery.set_viewXml('<View><Query><Where></Where><OrderBy><FieldRef Name=\'Title\' Ascending=\'TRUE\'/></OrderBy><ViewFields><FieldRef Name=\'Title\'/></ViewFields></Query></View>');
                                            
                        this.collListItem = oList.getItems(camlQuery);
                        clientContext.load(collListItem);

                        clientContext.executeQueryAsync(Function.createDelegate(this, function () { MyJSNamespace.onQuerySucceeded(); }), Function.createDelegate(this, MyJSNamespace.onQueryFailed));
                    });
               
            },

            onQuerySucceeded: function () {

                var listData = collListItem.get_data();
                var regions = [];
                if (listData.length > 0) {
                    for (var i = 0; listData.length > i; i++) {
                        var listItemObj = listData[i].get_fieldValues();
                        var region = listItemObj.Title; //use your field internal name
      
      //Unique titles are stored in 'regions' array
                        if ($.inArray(region, regions) == -1) {
                            regions.push(region); //only unique values
                        }
                    }
               
                }
            },

            onQueryFailed: function (sender, args) {
                alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
            }
         
        }

    })();
})();