在REST中验证列表项

Validate list item in REST

本文关键字:列表 验证 REST      更新时间:2023-09-26

我有一个函数,将使用REST添加列表项。但我想验证一个列表项目,如果它已经存在于我的列表之前,我添加它。怎么做呢?

function addListItem() {    
var title = $("#txtTitle").val();
var siteUrl = _spPageContextInfo.webAbsoluteUrl;
var fullUrl = siteUrl + "/_api/web/lists/GetByTitle('Employee')/items";
$.ajax({
    url: fullUrl,
    type: "POST",
    data: JSON.stringify({
        '__metadata': { 'type': 'SP.Data.EmployeeListItem' },   
        'EmployeeID': $("#txtEmpID").val(),
        'Name': $("#txtName").val(),
    }),
    headers: {
        "accept": "application/json;odata=verbose",
        "content-type": "application/json;odata=verbose",
        "X-RequestDigest": $("#__REQUESTDIGEST").val()
    },
    success: onQuerySucceeded,
    error: onQueryFailed
});
function onQuerySucceeded(sender, args) {
alert("Item successfully added!");
}
  function onQueryFailed() {
  alert('Error!');
}
 };

可以在SharePoint REST请求中使用OData查询操作在Get操作中使用$filter参数来验证用户是否存在于列表中,如下所示:

$filter=Name eq '<UserName>'

一个例子:

 siteUrl + "/_api/web/lists/GetByTitle('Employee')/items?$filter=Name eq 'John'

& lt;UserName>为文本框值

您可以在这里看到一个响应示例:

http://services.odata.org/Northwind/Northwind.svc/Customers? $过滤器=联系名称% 20 eq % 27玛丽亚% 20安德斯20% % 27

只需执行Get请求并计数元素以知道用户是否存在

$.get("/_api/web/lists/getbytitle('Employee')/items?$filter=Name eq '<Name>'",function(e){
    if($(e).find("entry").length > 0){
          console.log("user exists");
    }
})

您可以在这里看到使用JQuery/Javascript使用SharePoint 2013 REST端点的完整基本操作:

https://msdn.microsoft.com/en-us/library/office/jj164022.aspx