4

I'm new to JavaScript Object Model in SharePoint 2010 and want to get some idea of that. I wrote below code to get all list items of a SharePoint library. This works fine and return all items. But I want to store the result to a Javascript array. Because I use an API, it requires an array as param. Like JSArray=allDocs.getEnumerator();// Something like this Anyidea?

<script type="text/javascript">
    var allDocs;

    $('#btnDemo2').click(function () {
        var ctx = new SP.ClientContext.get_current();

        var targetList = ctx.get_web().get_lists().getByTitle('Shared Documents');
        var query = SP.CamlQuery.createAllItemsQuery();

        allDocs = targetList.getItems(query);
        ctx.load(allDocs);

        ctx.executeQueryAsync(Function.createDelegate(this, getDocsAllItemsSuccess),
            Function.createDelegate(this, getDocsAllItemsFailure));
    });

    function getDocsAllItemsSuccess(sender, args) {
        var listEnumerator = allDocs.getEnumerator();
        while (listEnumerator.moveNext()) {
            $('#demo2Result').append(listEnumerator.get_current().get_item("FileLeafRef") + '<br />');
        }
    }

    function getDocsAllItemsFailure(sender, args) {
        alert('Failed to get list items. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
    }
</script>
5

You'll get an array back if you use loadQuery rather than load. In the example below allDocs is an array.

var targetList = ctx.get_web().get_lists().getByTitle('Shared Documents');
var query = SP.CamlQuery.createAllItemsQuery();

var queryResults = targetList.getItems(query);
var allDocs = ctx.loadQuery(queryResults);
  • Didn't know of that method, but its actually the same type of collection you get from get_data(), a SP.ClientObjectCollection object – Anders Aune Jul 22 '14 at 5:46
  • sorry, I did mean an ArrayList :) – Anders Aune Jul 22 '14 at 5:54
  • Be careful though; the reason getItems returns something less convenient than an array is so that it can track changes to the items. If you use loadQuery, you'll have to manage this yourself. – jpaugh Jul 13 '17 at 17:08
2

You can get the result as an ArrayList using SP.ClientObjectCollection.data

Then you can access properties like this:

 var listEnumerator = allDocs.get_data();
listEnumerator[0].get_item("FileLeafRef")

Edit:

If you want an array with only FileLeafRef, you could do something like this:

var myArray2 = new Array(); 

allDocs.get_data().map(function(item) {
    myArray2.push(item.get_item("FileLeafRef"));
});
  • Thanks Anders. Is this fine? var listEnumerator = allDocs.getEnumerator(); var myArray2 = new Array(); myArray2 = allDocs.get_data(); myArray2[0] = listEnumerator.get_current().get_item("FileLeafRef"); – Sivakumar Piratheeban Jul 21 '14 at 6:20
1

I found the solution First things you need to create the required tags dynamically.I have made some correction in the above. I have three columns in the list and to fetch them and display individually,I have used three array and created dynamic tags

....Code is here...

var hostWebUrl;
var appWebUrl;
// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
$(document).ready(function () {




    hostWebUrl = decodeURIComponent(manageQueryStringParameter('SPHostUrl'));
    appWebUrl = decodeURIComponent(manageQueryStringParameter('SPAppWebUrl'));
    Fetchdata();



});

function manageQueryStringParameter(paramToRetrieve) {
    var params =
    document.URL.split("?")[1].split("&");
    var strParams = "";
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == paramToRetrieve) {
            return singleParam[1];
        }
    }
}


function Fetchdata() {
    var ctx = new SP.ClientContext(appWebUrl);//Get the SharePoint Context object based upon the URL  
    var appCtxSite = new SP.AppContextSite(ctx, hostWebUrl);
    var web = appCtxSite.get_web();
    var list = web.get_lists().getByTitle("Announcement");

   // var camlQuery = new SP.CamlQuery();
    //camlQuery.set_viewXml('<View><Query><Where><Geq><FieldRef Name=\'Title\'/>' +
    //    '<Value Type=\'Text\'>Annoucement1</Value></Geq></Where></Query><RowLimit>10</RowLimit></View>');
    collListItem = list.getItems("");

    ctx.load(collListItem);


    ctx.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));

}

function onQuerySucceeded(sender, args) {

    var listItemInfo1 = new Array();
    var listItemInfo2 = new Array();
    var listItemInfo3 = new Array();

    var itemCount = 0;

    var listItemEnumerator = collListItem.getEnumerator();
    while (listItemEnumerator.moveNext()) {


        var oListItem = listItemEnumerator.get_current();

        listItemInfo1[itemCount] = oListItem.get_item('Title');
        //alert(listItemInfo1);
        listItemInfo2[itemCount] = oListItem.get_item('Body');
        listItemInfo3[itemCount]= oListItem.get_item('Images').get_url();
        itemCount++;
        // alert(itemCount);


    }




        for (var i in listItemInfo1) {



        var parent = $('#announcement_slider');


        //Create a div
        var p1 = document.createElement('div');
        parent.append(p1);

        var images = document.createElement('img');
        $(images).attr('src', listItemInfo3[i]);

        $(images).attr('class', 'left mrg_right_10');

        var spanTag = document.createElement('span');

        var spanTag1 = document.createElement('span');
       // alert(listItemInfo3[i]);

        //alert(listItemInfo3[i]);

        spanTag.innerHTML = listItemInfo1[i].toString();
        spanTag1.innerHTML = listItemInfo2[i].toString();






        p1.appendChild(images);

        p1.appendChild(spanTag);
        p1.appendChild(spanTag1);




    }

        $('#announcement_slider').slidesjs({
            height: 50,
            play: {
                active: true,
                auto: true,
                interval: 6000,
                swap: true
            },
            navigation: {
                active: false
            }
        });




    }



function onQueryFailed(sender, args) {

    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
  • if you are doing ==while (listItemEnumerator.moveNext()) {} == inline with ==for (var i in listItemInfo1) {}== you don't need to the for loop, because your while is alreay your loop. – egidiocs Mar 16 '16 at 20:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.