SHAREPOINT 2010 READ FROM LIST USING ECMASCRIPT


/ Published in: JavaScript
Save to your folder(s)

This code works for me without requiring any includes, plugins, or service packs. It should also integrate seamlessly with jquery. If needing to perform this process more than once on a page, make sure namedListItem variable is unique for each case (use different names for that page-scoped variable in each case).

For caml queries, wrap Query tag in View tag.

For lookup fields use .get_lookupValue() property syntax. For example...

<pre>topNavSection[enm] = oListItem.get_item('Section').get_lookupValue();</pre>


Copy this code and paste it in your HTML
  1. <script type="text/javascript">
  2.  
  3. ExecuteOrDelayUntilScriptLoaded(functionName, "sp.js"); //this is necessary to ensure the library is loaded before function triggered
  4. var namedListItem;
  5.  
  6.  
  7. function functionName() {
  8.  
  9.  
  10. var clientContext = SP.ClientContext.get_current();
  11. //or use the syntax below for accessing a list that may not reside in the current site
  12. //var clientContext = new SP.ClientContext(rootUrl);
  13.  
  14. var myList = clientContext.get_web().get_lists().getByTitle('myList'); //actual list name here
  15.  
  16. var camlQuery = new SP.CamlQuery();
  17. camlQuery.set_viewXml(''); //caml statement goes here between the single quotes
  18. namedListItem = myList.getItems(camlQuery);
  19.  
  20. clientContext.load(namedListItem);
  21. //or use below to specify to load only the required properties for better performance
  22. //clientContext.load(namedListItem, 'Include(field1, field2)');
  23.  
  24. clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
  25. }
  26.  
  27. function onQuerySucceeded(sender, args) {
  28.  
  29. var listItemInfo = '';
  30.  
  31. var listItemEnumerator = namedListItem.getEnumerator();
  32.  
  33. while (listItemEnumerator.moveNext()) {
  34. var oListItem = listItemEnumerator.get_current();
  35. listItemInfo += '\nField1: ' + oListItem.get_item('field1') + ', Field2: ' + oListItem.get_item(' field2'); //replace field1 & field2 with actual column names
  36. }
  37.  
  38. alert(listItemInfo.toString());
  39. }
  40.  
  41. function onQueryFailed(sender, args) {
  42.  
  43. alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
  44. }
  45.  
  46. </script>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.