Thursday, 19 April 2012

Retrieve items from a View with CAML in Javascript Client Object model - SharePoint 2010


This is a simple code that took me a lot of time to write because of the complexity of the famous Javascript Client Object model i guess.

So here is the complete code to get items from one particular view using CAMl query in Javascript Client Object model.

<script type="text/ecmascript" language="ecmascript">

function runCode()

{

var context = new SP.ClientContext.get_current();

var list = context.get_web().get_lists().getByTitle("ListName ");

var view = list.get_views().getByTitle("ViewName");

context.load(view);

context.executeQueryAsync(

function (sender, args) { alert(view.get_viewQuery()); getItemsFromList("Projects", "<View><Query>" + view.get_viewQuery() + "</Query></View>") },

function (sender, args) { alert("error: " + args.get_message()); }

);

}

function getItemsFromList(listTitle, queryText)

{

var context = new SP.ClientContext.get_current();

var list = context.get_web().get_lists().getByTitle(listTitle);

var query = new SP.CamlQuery();

query.set_viewXml(queryText);

var items = list.getItems(query);

context.load(items);

context.executeQueryAsync(

function()

{

var listEnumerator = items.getEnumerator();

var i = 0;

while (listEnumerator.moveNext())

{

i++;

}

alert("items retrieved: " + i);

},

function(sender, args) {alert("error in inner request: " + args.get_message());}

);

}
</script>

<input id="Button1" type="button" value="Run Code" onclick="runCode()" />

Just relace ListName and ViewName in above code.

Update - See the updated post for detailed code on getting the item iteself
Retrieve items from view using SPquery\Caml sharepoint 2010

Ads by Google

No comments:

Post a Comment