Pan de Sal
Pan de Sal

Reputation: 9

How to get multiple lists using JSOM in sharepoint?

I have issue on retrieving multiple lists. Is there a way that I can use JSOM to make multiple request in different lists? Thank you.

Upvotes: 0

Views: 1773

Answers (1)

brroshan
brroshan

Reputation: 1650

Old question but I'd like to post this answer for future readers.

Just get all your lists then load them one after another:

var ctx = SP.ClientContext.get_current();

// assuming you're working with the appweb
var list1 = ctx.get_web().get_lists().getByTitle("list1");
var list2 = ctx.get_web().get_lists().getByTitle("list2");
var list3 = ctx.get_web().get_lists().getByTitle("list3");

ctx.load(list1);
ctx.load(list2);
ctx.load(list3); // multiple loads required

ctx.executeQueryAsync( // one call to the server
         function(){
            // do something with the lists
         },
         function(){
            // fail
         });

Also a good idea to utilize jQuery's promise pattern when working with SharePoint's JSOM api, like so:

// extending the jQuery namespace for convenience
// if this is a bad idea performance wise or something
// I would like to hear from someone :)
$.extend({    

execQAsync: function(ctx){
   var dfd = $.Deferred();

   ctx.executeQueryAsync(
       function(sender,args){
           dfd.resolve();
       },
       function(sender, args){
           dfd.reject();
       });

    return dfd.Promise();
   }

});

Then you can go about doing things this way:

$.execQAsync(ctx)
 .done(function(){
     // do something when the promise resolves
 })
 .fail(function(){arguments[1].get_message() });

See Optimal/preferred way to call 'SP.ClientContext.executeQueryAsync' in SharePoint

P.S Doublecheck lettercasings etc, i wrote all this in a fiddle.

Upvotes: 1

Related Questions