In this post I will explain how to retrieve SharePoint list items using Client OM. To get items from a list using ECMA Script we can use below two functions
1. getItemsById (id) - return a single item.
2. getItems(query)- return multiple items
In this post we will retrieve list items using getItemsById () function.
Step 1: Create a custom list and name it as Employees.
Step 2: Rename Title column as FirstName, Add LastName, and WorkingUnit columns.
Step 3: Add content editor web part and add the below code
<script type="text/ecmascript">
ExecuteOrDelayUntilScriptLoaded(RetrieveListItems, "sp.js");
function RetrieveListItems()
{
var clientContext = new SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle('Employees');
this.oListItem = oList.getItemById(1);
clientContext.load(this.oListItem);
clientContext.executeQueryAsync(Function.createDelegate(this,this.OnSuccess), Function.createDelegate(this, this.OnFailure));
}
function OnSuccess()
{
var listItemInfo ='';
var Html ='';
Html += '<table cellspacing="'+3+'" cellpadding="'+3+'" border="'+0+'"><tr><td>ID</td><td>First Name</td><td>Last Name</td><td>Department</td></tr>'+
'<tr><td>'+oListItem.get_id()+'</td><td>'+oListItem.get_item('Title')+'</td><td>'+oListItem.get_item('LastName')+'</td><td>'+
oListItem.get_item('WorkingUnit')+'</td></tr></table>';
document.getElementById('ECMADiv').innerHTML =Html;
}
function OnFailure(sender, args)
{
alert('Request failed. ' + args.get_message() + '\n' +
args.get_stackTrace());
}
</script>
Step 4: Add HTML Form web part and add below code
<table cellspacing="3" cellpadding="3" border="2">
<tbody><tr><td style="background-color:#f9f9f9"><div>
<div id="ECMADiv"></div>
</div></td>
</tr>
</tbody></table>
No comments:
Post a Comment