加载JQuery:
将JS文件加载到SharePoint环境中的方法
SharePoint Client Object Model基础:
1. 使用Client Object Model之前需要加载sp.js文件,加载方法:
SharePoint 2010:
$(document).ready(function(){ ExecuteOrDelayUntilScriptLoaded(MyFunction, "sp.js"); }); function MyFunction(){ ... }
$(document).ready(function(){ SP.SOD.executeFunc("sp.js", "SP.ClientContext", MyFunction); }); function MyFunction(){ ... }
获取当前ClientContext对象:
var context = new SP.ClientContext.get_current();获取当前web对象:
var web = context.get_web(); context.load(web); context.executeQueryAsync(SucceedFunction, FailedFunction); //执行异步查询获取web的信息,SucceedFunction和FailedFunction是回调函数。获取title为“abc”的列表:
var web = context.get_web(); var list = web.get_lists().getByTitle("abc"); context.load(list); context.executeQueryAsync(SucceedFunction, FailedFunction); //执行异步查询获取list的信息获取id为1的item:
var item = list.getItemById("1");获取所有的item:
var web = context.get_web(); var list = web.get_lists().getByTitle("abc"); var allItems = list.getItems(""); context.load(allItems, 'include(ID, Title)'); //使用include指定获取的field信息 context.executeQueryAsync(SucceedFunction, FailedFunction); //执行异步查询获取所有的item遍历所有item:
var itemCollection = allItems.getEnumerator(); while(itemCollection.moveNext()) { var myItem = itemCollection.get_current(); ... ... }获取item的field值:
var title = myItem.get_item('Title'); //参数是field的internal name更新item的field值:
myItem.set_item('Title', 'new title'); myItem.update();删除一个item:
myItem.deleteObject(); context.executeQueryAsync(SucceedFunction, FailedFunction);处理异步查询的异常:
function FailedFunction(sender, args){ //使用args参数获得具体的错误信息 alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace()); }向list中添加一条item:
var context = new SP.ClientContext.get_current(); var web = context.get_web(); var list = web.get_lists().getByTitle("abc"); var listItemInfo = new SP.ListItemCreationInformation(); //创建一个ListItemCreationInformation对象 var listItem = list.addItem(listItemInfo); //添加item listItem.set_item('Title', 'new item'); //设置item的title listItem.update(); context.executeQueryAsync(SucceedFunction, FailedFunction); //执行异步查询,在list中创建item
使用ajax调用web service,获取“Task”列表中的items,并且遍历显示Title字段:
function LoadItems() { var taskUrl = "/_vti_bin/ListData.svc/Task/"; //如果Task列表位于子站点sub中,这里需要使用/sub/_vti_bin/ListData.svc/Task/ $.ajax({ type: 'GET', url: taskUrl, dataType: 'json', success: function(data) { //成功的返回值是data对象,其中的d的results属性包含item $.each(data.d.results, function(i, result) { alert('Title: '+result.Title); }); }); }, error: function() { alert("error"); } }); }
function LoadItem(id) { var itemUrl = "/_vti_bin/ListData.svc/Task(" + id + ")"; $.getJSON(itemUrl, function(data) { alert($(data.d.Title)); }); }