Rest API 操作List Items
获取所有的List Items
function getItems(url) { $.ajax({ url: url, type: "GET", headers: { "accept": "application/json;odata=verbose", }, success: function(data) { //console.log(data); for(var i=0;i<data.d.results.length;i++){ console.log(data.d.results[i].Number); } if (data.d.__next) { getItems(data.d.__next); } }, error: function(jqxhr) { alert(jqxhr.responseText); } }); } getItems(_spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Association')/items");
删除所有的List Items: (获取所有的list Items可以使用上面的方法)
function deleteItem(url,prm) { $.ajax({ url: _spPageContextInfo.webAbsoluteUrl + url, type: "DELETE", headers: { "accept": "application/json;odata=verbose", "X-RequestDigest": $("#__REQUESTDIGEST").val(), "If-Match": "*" }, success: function (data) { console.log(prm); }, error: function (error) { alert(JSON.stringify(error)); } }); } $.ajax({ url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Association')/items?$filter=Number%20ne%20%27120%27&$top=2000", type: "GET", headers: { "accept": "application/json;odata=verbose", }, success: function (data) { var items = data.d.results; console.log(items.length); for(var i=0;i<items.length;i++){ var url = "/_api/Web/Lists/getByTitle('Association')/getItemById("+items[i].ID+")"; deleteItem(url,items[i].ID); } }, error: function (error) { alert(JSON.stringify(error)); } });
删除单个:
function deleteListItem() { var id = $("#txtId").val(); var siteUrl = _spPageContextInfo.webAbsoluteUrl; var fullUrl = siteUrl + "/_api/web/lists/GetByTitle('MyCompanyInfo')/items(" + id + ")"; $.ajax({ url: fullUrl, type: "POST", headers: { "accept": "application/json;odata=verbose", "content-type": "application/json;odata=verbose", "X-RequestDigest": $("#__REQUESTDIGEST").val(), "X-HTTP-Method": "DELETE", "IF-MATCH": "*" }, success: onQuerySucceeded, error: onQueryFailed }); } function onQuerySucceeded(sender, args) { $("#divResult").html("Item successfully deleted!"); } function onQueryFailed() { alert('Error!'); }
添加List Items:
function addListItem() { var title = $("#txtTitle").val(); var industry = $("#txtIndustry").val(); var siteUrl = _spPageContextInfo.webAbsoluteUrl; var fullUrl = siteUrl + "/_api/web/lists/GetByTitle('MyAssociation')/items"; var itemType = GetItemTypeForListName(listName); $.ajax({ url: fullUrl, type: "POST", data: JSON.stringify({ '__metadata': { 'type': itemType },//'SP.Data.MyAssociationListItem' 'Title': title, 'Industry': industry }), headers: { "accept": "application/json;odata=verbose", "content-type": "application/json;odata=verbose", "X-RequestDigest": $("#__REQUESTDIGEST").val() }, success: onQuerySucceeded, error: onQueryFailed }); } function onQuerySucceeded(sender, args) { $("#divResult").html("Item successfully added!"); } function onQueryFailed() { alert('Error!'); } // Get List Item Type metadata function GetItemTypeForListName(name) { return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem"; }
Update List Items:
ExecuteOrDelayUntilScriptLoaded(initializePage, "sp.js"); function initializePage() { var siteURL; var itemsArray = []; // This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model $(document).ready(function() { var scriptbase = _spPageContextInfo.webServerRelativeUrl + "/_layouts/15/"; UpdateListItem(); }); } //Retrieve list items from sharepoint using API function UpdateListItem() { siteURL = _spPageContextInfo.webAbsoluteUrl; console.log("from top nav - " + siteURL); var apiPath = siteURL + "/_api/lists/getbytitle(''samplelist'')/items/getbyid(1)"; $.ajax({ url: apiPath, type: "POST", headers: { Accept: "application/json;odata=verbose" }, data: "{__metadata:{'type':'SP.Data.YourlistnameListItem'},Title:”Ur input " } ", async: false, success: function(data) { alert("Item updated successfully"); }, eror: function(data) { console.log("An error occurred. Please try again."); } }); }
How to update List Item via SharePoint REST interface:
function updateJson(endpointUri,payload, success, error) { $.ajax({ url: endpointUri, type: "POST", data: JSON.stringify(payload), contentType: "application/json;odata=verbose", headers: { "Accept": "application/json;odata=verbose", "X-RequestDigest" : $("#__REQUESTDIGEST").val(), "X-HTTP-Method": "MERGE", "If-Match": "*" }, success: success, error: error }); } function getItemTypeForListName(name) { return"SP.Data." + name.charAt(0).toUpperCase() + name.slice(1) + "ListItem"; } function updateListItem(webUrl,listTitle,listItemId,itemProperties,success,failure) { var listItemUri = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/items(" + listItemId + ")"; var itemPayload = { '__metadata': {'type': getItemTypeForListName(listTitle)} }; for(var prop in itemProperties){ itemPayload[prop] = itemProperties[prop]; } updateJson(listItemUri,itemPayload,success,failure); } Usage: var itemProperties = {'Title':'John Doe'}; updateListItem(_spPageContextInfo.webAbsoluteUrl,'Contacts',1,itemProperties,printInfo,logError); function printInfo() { console.log('Item has been created'); } function logError(error){ console.log(JSON.stringify(error)); }
获取所有的List Items Count:
_spPageContextInfo.webAbsoluteUrl+" _api/web/lists/getByTitle('DepartProd')/itemcount" //?$filter=AssignedTo/ID eq 2