SharePoint 2013 Odata 常用实例和基本操作

   

       

本文讲述SharePoint 2013 Odata 常用实例和基本操作。

Open Data Protocol (OData)是一个基于Rest风格的数据服务,同过这个服务可以使用同一的URI定位到具体的资源(文件和记录等),从而使得这些资源可以使用HTTP请求进行增删改查,它定义了一系列的规则,使得资源更容易被定位和操作。

首先看一下OData定义的URI结构:

那么相对SharePoint 2013,一个简单的实例为:

http://moss2013site/_api/web/lists/GetByTitle('News')/items?$select=Title,Body,ID&$top=10&$orderby=Created desc

这个URI表示查询News 列表里面最新的10条记录,查询的字段为Title,Body,ID

http://moss2013site/_api/web 是service root URI

/lists/GetByTitle('News')/items 是resource path

?$select=Title,Body,ID&$top=10&$orderby=Created desc 是Query option, $select=Title,Body,ID表示选择Title,Body,ID三个字段,$top=10表示选择前10条记录,$orderby=Created desc表示按创建时间倒序排列

service root URI 和 resource path相对简单和容易理解,这里我们用一张来自微软网站http://msdn.microsoft.com/en-us/library/office/apps/fp142385.aspx的图来说明下Query option(注意降序排列不时dsc,应该是desc,如果你使用dsc将会报错),目前SharePoint 2013 的Odata service支持以下查询选项:

SharePoint 2013 的Odata service的常用URI实例:

URI实例 解释
_api/web/title 返回web title 
_api/web/lists(guid'<list id>') 返回列表
_api/web/lists/getByTitle('Announcements')/fields 返回列表的所有字段
_api/web/lists/getByTitle('Task')/items 返回Tas列表的所有item
_api/web/siteusers 返回该站点所有用户
_api/web/sitegroups 返回该站点所有用户组
_api/web/sitegroups(3)/users 返回该站点所有在id为3的用户组的用户
_api/web/GetFolderByServerRelativeUrl('/Shared Documents') 返回Shared Documents文档库根目录
_api/web/GetFolderByServerRelativeUrl('/Plans')/Files('a.txt')/$value 返回Plans文档库根目录下的a.txt文件

带Query option的实例:

查询选项 作用
$select 指定返回字段(列)
$filter 指定过滤条件
$expand 用于关联列表,指定返回关联字段(列)
$top 指定返回前N条记录
$skip 指定返回结果跳过前N行记录
$orderby 指定按某个字段排序
URI实例 解释
_api/web/lists/getByTitle(
  'Books')/items?$select=Title,PublishedBy/Name&$expand=PublishedBy
前提book里面有个
PublishedBy 的字段关联到Publisher 列表

返回Books列表的Title和关联
Publisher 列表项目的Name
_api/web/lists/getByTitle('Books')/items?$top=10&$skip=2
返回Books列表的3~10项纪录
_api/web/lists/getByTitle('Books')/items?$skip=2&$top=10
返回Books列表的3~12项纪录
_api/web/lists/getByTitle('Books')/items?$orderby=ID desc&$top=2
返回Books列表的最后两条记录
_api/web/lists/getByTitle(
  'Books')/items?$select=Title&$filter=Author eq 'Mark Twain'&$top=2
返回Author 等于
 'Mark Twain'的头两条记录
_api/web/lists/getByTitle('Books')/items?$orderby=Title asc
返回Books列表的所有记录并按Title升序排列
_api/web/lists/getByTitle('Books')/items?$select=Author,Title,ISBN
返回Books列表下记录(只返回列
Author,Title,ISBN

使用JQuery + Odata实现增删改查

按Json格式查询:

  1. function onGetCustomer(customerId) {  
  2.    
  3.   // begin work to call across network  
  4.   var requestUri = _spPageContextInfo.webAbsoluteUrl +  
  5.                 "/_api/Web/Lists/getByTitle('Customers')/items(" + customerId + ")";  
  6.    
  7.   // execute AJAX request  
  8.   $.ajax({  
  9.     url: requestUri,  
  10.     type: "GET",  
  11.     headers: { "ACCEPT": "application/json;odata=verbose" },  
  12.     success: function(data){  
  13.       alert(data.d.FirstName);  
  14.     },  
  15.     error:  function(){  
  16.       alert("Failed to get customer");  
  17.     }  
  18.   });  
  19. }  
function onGetCustomer(customerId) {
 
  // begin work to call across network
  var requestUri = _spPageContextInfo.webAbsoluteUrl +
                "/_api/Web/Lists/getByTitle('Customers')/items(" + customerId + ")";
 
  // execute AJAX request
  $.ajax({
    url: requestUri,
    type: "GET",
    headers: { "ACCEPT": "application/json;odata=verbose" },
    success: function(data){
      alert(data.d.FirstName);
    },
    error:  function(){
      alert("Failed to get customer");
    }
  });
}

添加:

  1. function onAddCustomer() {  
  2.   
  3.     var requestUri = _spPageContextInfo.webAbsoluteUrl +  
  4.               "/_api/Web/Lists/getByTitle('Customers')/items/";  
  5.   
  6.     var requestHeaders = {  
  7.       "ACCEPT": "application/json;odata=verbose",  
  8.       "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
  9.     }  
  10.   
  11.     var customerData = {  
  12.       __metadata: { "type": "SP.Data.CustomersListItem" },  
  13.       FirstName: "Paul"  
  14.     };  
  15.   
  16.     requestBody = JSON.stringify(customerData);  
  17.   
  18.     $.ajax({  
  19.       url: requestUri,  
  20.       type: "Post",  
  21.       contentType: "application/json;odata=verbose",  
  22.       headers: requestHeaders,  
  23.       data: requestBody,  
  24.       success: function(){  
  25.         alert("Created customer");  
  26.       },  
  27.       error: function(){  
  28.         alert("Failed to create customer");  
  29.       }  
  30.     });  
  31.   }  
  32. }  
function onAddCustomer() {

    var requestUri = _spPageContextInfo.webAbsoluteUrl +
              "/_api/Web/Lists/getByTitle('Customers')/items/";

    var requestHeaders = {
      "ACCEPT": "application/json;odata=verbose",
      "X-RequestDigest": $("#__REQUESTDIGEST").val(),
    }

    var customerData = {
      __metadata: { "type": "SP.Data.CustomersListItem" },
      FirstName: "Paul"
    };

    requestBody = JSON.stringify(customerData);

    $.ajax({
      url: requestUri,
      type: "Post",
      contentType: "application/json;odata=verbose",
      headers: requestHeaders,
      data: requestBody,
      success: function(){
        alert("Created customer");
      },
      error: function(){
        alert("Failed to create customer");
      }
    });
  }
}

删除:

  1. function onDeleteCustomer(customerId) {  
  2.   
  3.   var requestUri = _spPageContextInfo.webAbsoluteUrl +  
  4.                 "/_api/Web/Lists/getByTitle('Customers')/items(" + customerId + ")";  
  5.   
  6.   var requestHeaders = {  
  7.     "ACCEPT": "application/json;odata=verbose",  
  8.     "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
  9.     "If-Match": "*" // delete the item even if another user has updated it since we last fetched it  
  10.   }  
  11.   
  12.   $.ajax({  
  13.     url: requestUri,  
  14.     type: "DELETE",  
  15.     contentType: "application/json;odata=verbose",  
  16.     headers: requestHeaders,  
  17.     success: function(){  
  18.       alert("Deleted customer");  
  19.     },  
  20.     error: function(){  
  21.       alert("Failed to delete customer");  
  22.     }  
  23.   });  
  24.   
  25. }  
function onDeleteCustomer(customerId) {

  var requestUri = _spPageContextInfo.webAbsoluteUrl +
                "/_api/Web/Lists/getByTitle('Customers')/items(" + customerId + ")";

  var requestHeaders = {
    "ACCEPT": "application/json;odata=verbose",
    "X-RequestDigest": $("#__REQUESTDIGEST").val(),
    "If-Match": "*" // delete the item even if another user has updated it since we last fetched it
  }

  $.ajax({
    url: requestUri,
    type: "DELETE",
    contentType: "application/json;odata=verbose",
    headers: requestHeaders,
    success: function(){
      alert("Deleted customer");
    },
    error: function(){
      alert("Failed to delete customer");
    }
  });

}

修改:

  1. function onUpdateCustomer(customerId, firstName) {  
  2.   // first we need to fetch the eTag to ensure we have the most recent value for it  
  3.   var requestUri = _spPageContextInfo.webAbsoluteUrl +  
  4.                 "/_api/Web/Lists/getByTitle('Customers')/items(" + customerId + ")";  
  5.    
  6.   // execute AJAX request  
  7.   $.ajax({  
  8.     url: requestUri,  
  9.     type: "GET",  
  10.     headers: { "ACCEPT": "application/json;odata=verbose" },  
  11.     success: function(data){  
  12.       // got the eTag  
  13.       var etag = data.d.etag;  
  14.     
  15.       var requestUri = _spPageContextInfo.webAbsoluteUrl +  
  16.                 "/_api/Web/Lists/getByTitle('Customers')/items(" + customerId + ")";  
  17.         
  18.       // set the MERGE verb so we only need to provide the update delta  
  19.       var requestHeaders = {  
  20.         "ACCEPT": "application/json;odata=verbose",  
  21.         "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
  22.         "X-HTTP-Method": "MERGE",  
  23.         "If-Match": etag  
  24.       }  
  25.     
  26.       var customerData = {  
  27.         __metadata: { "type": "SP.Data.CustomersListItem" },  
  28.         FirstName: firstName  
  29.       };  
  30.     
  31.       requestBody = JSON.stringify(customerData);  
  32.     
  33.       $.ajax({  
  34.         url: requestUri,  
  35.         type: "POST",  
  36.         contentType: "application/json;odata=verbose",  
  37.         headers: requestHeaders,  
  38.         data: requestBody,  
  39.         success: function(data){  
  40.           alert("Updated customer");  
  41.         },  
  42.         error: function(data){  
  43.           alert("Failed to update customer");  
  44.         }  
  45.       });  
  46.     },  
  47.     error:  function(data){  
  48.       alert("Failed to get customer eTag");  
  49.     }  
  50.   });  
  51. }  
function onUpdateCustomer(customerId, firstName) {
  // first we need to fetch the eTag to ensure we have the most recent value for it
  var requestUri = _spPageContextInfo.webAbsoluteUrl +
                "/_api/Web/Lists/getByTitle('Customers')/items(" + customerId + ")";
 
  // execute AJAX request
  $.ajax({
    url: requestUri,
    type: "GET",
    headers: { "ACCEPT": "application/json;odata=verbose" },
    success: function(data){
      // got the eTag
      var etag = data.d.etag;
  
      var requestUri = _spPageContextInfo.webAbsoluteUrl +
                "/_api/Web/Lists/getByTitle('Customers')/items(" + customerId + ")";
      
      // set the MERGE verb so we only need to provide the update delta
      var requestHeaders = {
        "ACCEPT": "application/json;odata=verbose",
        "X-RequestDigest": $("#__REQUESTDIGEST").val(),
        "X-HTTP-Method": "MERGE",
        "If-Match": etag
      }
  
      var customerData = {
        __metadata: { "type": "SP.Data.CustomersListItem" },
        FirstName: firstName
      };
  
      requestBody = JSON.stringify(customerData);
  
      $.ajax({
        url: requestUri,
        type: "POST",
        contentType: "application/json;odata=verbose",
        headers: requestHeaders,
        data: requestBody,
        success: function(data){
          alert("Updated customer");
        },
        error: function(data){
          alert("Failed to update customer");
        }
      });
    },
    error:  function(data){
      alert("Failed to get customer eTag");
    }
  });
}
原文地址:https://www.cnblogs.com/ningang/p/4299103.html