您的位置:首页 > Web前端 > JavaScript

Accessing List Data using the JavaScript Client OM

2010-04-15 18:07 465 查看

This example illustrates how to use the ECMAScript client side object model to update and read list data dynamically. Also shown is how to use the new Dialog API’s from client side script.

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls"
Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages"
Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="VisualWebPart1UserControl.ascx.cs"
Inherits="ScriptOMExample.VisualWebPart1.VisualWebPart1UserControl" %>
<SharePoint:ScriptLink ID="ScriptLink1" runat="server" Name="sp.js" Localizable="false"
LoadAfterUI="true" />

<script type="text/javascript">

/* SharePoint list names */
var ContactsListName = "Contacts List";
var CompanyListName = "Company List";

/* SharePoint list field names */
var CompanyNameField = "Title";
var CompanyPhoneField = "Company_x0020_Phone_x0020_Number";
var CompanyDescriptionField = "Company_x0020_Description";
var ContactFirstNameField = "First_x0020_Name";
var ContactTitleField = "Title";
var ContactLastNameField = "Last_x0020_Name";
var ContactEmailField = "E_x002d_Mail";
var ContactCompanyListField = "Company_x0020_List";

/* List objects */
var contactsList;
var companyList;

/* variable to hold list items from the contactsList */
var contacts;

/* client context object – used to access SharePoint data */
var context;

/* web (SPWeb) that our page is running on */
var web;

/* variable to hold modalDialog to close later */
var modalDialog;

/* used when creating a new contactListItem
need to reference the Id field for setting the fieldLookupValue. */
var companyListItem;
var copyOfAddCompanyForm;

/* our startup method when the page loads */
_spBodyOnLoadFunctionNames.push("Initialize()");

/* Initialize useful variables and retrieve ClientContext */
function Initialize() {
/* Retrieves the current ClientContext object */
context = SP.ClientContext.get_current();
web = context.get_web();

// Get references to the lists we will use
contactsList = web.get_lists().getByTitle(ContactsListName);
companyList = web.get_lists().getByTitle(CompanyListName);

// Get the list items for the contacts list
contacts = contactsList.getItems();

// context.load tells the object model to load the objects scalar
// properties. Otherwise they will not be accessible
context.load(contacts);
context.load(contactsList);
context.executeQueryAsync(onListsLoaded);
}

/* Event handler called loading the contacts and companies lists

This method dynamically renders an HTML table to display the list data */

function onListsLoaded() {
var contactCount = contactsList.get_itemCount();
var companyTable = document.getElementById("tblCompanyList");

// clear out the table so when we add a new company there are not duplicates
while (companyTable.rows.length > 0)
companyTable.deleteRow(companyTable.rows.length - 1);
var row = new Array();
var content;
var cell;
var tbo = document.createElement("tbody");

// Loop for each contact
for (contactIndex = 0; contactIndex < contactCount; contactIndex++) {
// For each contact create a row in the table
row[contactIndex] = document.createElement("tr");

// itemAt() retrieves the listitem
var contactLI = contacts.itemAt(contactIndex);

// get_item() retrieves the listitem value
// if the listitem value is from a lookup field we call get_lookupValue()
var companyName =
contactLI.get_item(ContactCompanyListField).get_lookupValue();

var companyPhone = contactLI.get_item(CompanyPhoneField).get_lookupValue();

var companyDesc =
contactLI.get_item(CompanyDescriptionField).get_lookupValue();
var companyContact = contactLI.get_item(ContactFirstNameField) + " " +
contactLI.get_item(ContactLastNameField);

var companyContactEmail = contactLI.get_item(ContactEmailField);
// add the cells for the row
cell = document.createElement("td");
content = document.createTextNode(companyName);
cell.appendChild(content);
row[contactIndex].appendChild(cell);
cell = document.createElement("td");
content = document.createTextNode(companyPhone);
cell.appendChild(content);
row[contactIndex].appendChild(cell);
cell = document.createElement("td");
content = document.createTextNode(companyDesc);
cell.appendChild(content);
row[contactIndex].appendChild(cell);
cell = document.createElement("td");
content = document.createTextNode(companyContact);
cell.appendChild(content);
row[contactIndex].appendChild(cell);
cell = document.createElement("td");
content = document.createTextNode(companyContactEmail);
cell.appendChild(content);
row[contactIndex].appendChild(cell);

// Add the row to the table body
tbo.appendChild(row[contactIndex]);
}

// add the table body to the table
companyTable.appendChild(tbo);
}

/* Hide the modal dialog and display the updated UI */

//function onContactAdded() {

//    HideAddCompany();

//}

/* Show a modalDialog with the contents of divAddCompany */

function ShowAddCompany() {

var divAddCompany = document.getElementById("divAddCompany");

// showModalDialog removes the element passed in from the DOM

// so we save a copy and add it back later

copyOfAddCompanyForm = divAddCompany.cloneNode(true);

divAddCompany.style.display = "block";

var options = { html: divAddCompany, width: 200, height: 350, dialogReturnValueCallback: ReAddClonedForm };

modalDialog = SP.UI.ModalDialog.showModalDialog(options);

}

/* Close the modalDialog */

function HideAddCompany() {

modalDialog.close();

Initialize();

}

function ReAddClonedForm() {

document.body.appendChild(copyOfAddCompanyForm);

}

/* Called from the Add Company modal dialog

Creates a list item in the Company List list and when that query is executed

onCompanyAdded creates the contact list item. */

function AddCompany() {

var lici1 = new SP.ListItemCreationInformation();

companyListItem = companyList.addItem(lici1);

companyListItem.set_item(CompanyNameField, getTBValue("txtCompanyName"));

companyListItem.set_item(CompanyPhoneField, getTBValue("txtPhoneNumber"));

companyListItem.set_item(CompanyDescriptionField, getTBValue("txtDescription"));

companyListItem.update();

context.load(companyListItem);

// Execute the query to create the company list

// onCompanyAdded is our call back method called when the call to the server has completed

// context.executeQuery(onCompanyAdded, OnError);
context.executeQueryAsync(onCompanyAdded, OnError);

}

/* Called when AddCompany has finished executing

Note we have to wait until completion because we need access to companyListItem

to set the correct lookupId */

function onCompanyAdded(args) {

var lici = new SP.ListItemCreationInformation();

var companyLookupField = new SP.FieldLookupValue();

companyLookupField.set_lookupId(companyListItem.get_id());

var contactListItem = contactsList.addItem(lici);

contactListItem.set_item(ContactTitleField, getTBValue("txtContactTitle"));

contactListItem.set_item(ContactFirstNameField, getTBValue("txtFirstName"));

contactListItem.set_item(ContactLastNameField, getTBValue("txtLastName"));

contactListItem.set_item(ContactEmailField, getTBValue("txtEMail"));

contactListItem.set_item(ContactCompanyListField, companyLookupField);

contactListItem.update();

context.executeQuery(onContactAdded);

}

/* Hide the modal dialog and display the updated UI */

function onContactAdded() {

HideAddCompany();

}

/* Error handler */

function OnError(sender, args) {

var spnError = document.getElementById("spnError");

spnError.innerHTML = args.get_message();

}

/* Helper function – shortcut to the value property of a textbox */

function getTBValue(elID) {

var el = document.getElementById(elID);

return el.value;

}

</script>
<div style="font-weight: bold">Company List</div>

<br />

<table id="tblCompanyList" style="border: solid 1px silver">

</table>

<br />

<a href="javascript:ShowAddCompany()">Add a company</a>

<br />

<div id="divAddCompany" style="display: none; padding: 5px">

<b>Company Information</b><br /><br />

Name <br />

<input type="text" id="txtCompanyName" /><br />

Phone Number<br />

<input type="text" id="txtPhoneNumber" /><br />

Description<br />

<input type="text" id="txtDescription" /><br />

<b>Contact Information</b><br /><br />

Title<br />

<input type="text" id="txtContactTitle" /><br />

First Name<br />

<input type="text" id="txtFirstName" /><br />

Last Name<br />

<input type="text" id="txtLastName" /><br />

E-Mail<br />

<input type="text" id="txtEMail" /><br />

<span id="spnError" style="color: Red" /><br />

<input type="button" value="Add New Company" onclick="AddCompany()" />

</div>

reference:accessing-list-data-using-the-javascript-client-om
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐