javascript - SharePoint 2013 客户端上下文 : How to DELETE specific list items by MULTIPLE CONDITION filter?

标签 javascript rest sharepoint sharepoint-2013 csom

通过从 Javascript 端使用 SP.ClientContext,下面是我用来“更新”列表项的代码。简单地:

    var clientContext = new SP.ClientContext( siteURL );
    spList = clientContext.get_web().get_lists().getByTitle( myListName );

    this.spList_ExistingItem = spList.getItemById( itemID );
    spList_ExistingItem.set_item( 'FullName', myFullName );
    spList_ExistingItem.set_item( 'Age', myAge );

    spList_ExistingItem.update();
    clientContext.executeQueryAsync(succeeded_handler, fail_handler);

这允许我更新一个列表项通过一个条件查询它:getItemById(itemID)这里。

现在假设我要删除任何项目:

  • 年龄 = 30
  • 国家=美国

那么我如何使用多个条件进行这样的查询。然后还要删除好吗?


已更新


根据下面的回答,我发现与 CSOM 相比,REST API 对于客户端/Javascript 端使用起来更容易、更清晰。 (那么,当然我已经将所有代码更改为 REST API 方式。)

所以结论是,我建议使用 REST API 而不是 CSOM (SP.ClientContext)。

谢谢! :)

最佳答案

这可以通过两种不同的方式完成,使用 CSOM/JSOM 或通过 SharePoint REST API。由于您在问题中使用的是 CSOM/JSOM 模型,因此我只会向您展示如何使用该方法完成。

使用 CSOM/JSOM

要在多个条件下过滤 SP.ListItem,没有将参数作为多个过滤字段的单一方法。相反,您将不得不求助于使用 CAML 查询来指定您想要的列表项,如下所示。

var clientContext = new SP.ClientContext( siteURL );
spList = clientContext.get_web().get_lists().getByTitle( myListName );

//Create a CAML-query with your filter conditions
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><And><Eq><FieldRef Name=\'Age\'/>' + 
    '<Value Type=\'Number\'>30</Value></Eq>
    <Eq><FieldRef Name=\'Country\'/>' + 
    '<Value Type=\'Text\'>US</Value></Eq></And></Where></Query><RowLimit>10</RowLimit></View>');

//The query will return a collection of items matching your conditions
this.collListItem = spList.getItems(camlQuery);

clientContext.load(collListItem);

//Execute the query
clientContext.executeQueryAsync(function () {

    var itemCount = collListItem.get_count();
    //For each list item in the collection, mark it to be deleted
    for (var i = itemCount - 1; i >= 0; i--) {
        var oListItem = collListItem.itemAt(i);
        oListItem.deleteObject();
    };

    //Execute the delete operation
    clientContext.executeQueryAsync(deleteSucceeded, deleteFailed);
}, fail_handler);

使用 SharePoint REST API

此方法假定您使用 jQuery 来执行一些简单的 $.ajax() 调用并使用 promise 功能,因为您可能有多个项目要删除。它还假设您了解如何使用 jquery 延迟对象来链接异步函数以按顺序运行。

简单的想法是

  1. 向 REST api 发出请求并获取所有符合您过滤条件的项目
  2. 对于返回的集合中的每个对象,发出另一个删除该项目的请求,并将该请求添加到请求数组中
  3. 完成所有请求后,做任何你想做的事!

请注意,您可能必须修改 REST api 调用以匹配您的列。只需使用浏览器或 Postman 来检查您的请求是否正确。


function getItemsToDelete () {
    //You might have to modify this so it filters correctly on your columns
    var requestUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle(" + myListName + ")/items?$filter=Age eq 30 and Country eq 'US'")

    //Return and ajax request (promise)
    return $.ajax({
        url: requestUrl,
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        },
        success: function(result) {
            $.each(result.d.results, function(index, item){
                //Note that we push the ajax-request to the array
                //that has been declared a bit down
                itemsToDelete.push(deleteItem(item));
            });            
        },
        error: function(error) {
            //Something went wrong when retrieving the list items
        }
    });    
}

function deleteItem (item) {
    //All SP.ListItems holds metadata that can be accessed in the '__metadata' attribute
    var requestUrl = item.__metadata.uri;

    return $.ajax({
        url: requestUrl,
        type: "POST",
        headers: {
            "accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "IF-MATCH": item.__metadata.etag,
            "X-HTTP-Method": "DELETE"
        },
        success: function() {
            console.log("Item with ID " + item.__metadata.id + " successfully deleted!");
        },
        error: function(error) {
            //Something went wrong when trying to delete the item
        }
    });    
}


//Declare an array of deferred objects that hold a delete request
//for each item that is to be deleted
var itemsToDelete = [];

//First get the items to delete
$.when(getItemsToDelete()).then(function () {
    $.when.apply($, itemsToDelete).then(function(){
        console.log("All items are deleted!");
    });
});

一些有用的资源

jQuery Deferred object CRUD operations on list items with SharePoint REST api

关于javascript - SharePoint 2013 客户端上下文 : How to DELETE specific list items by MULTIPLE CONDITION filter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31452356/

相关文章:

javascript - 替换 HTML 元素中的字符

http - 根据我们域中定义的规则,Http 状态代码 412 是否适合错误

javascript - 使用客户端对象模型 (CSOM) 获取 Sharepoint 选定列表项

c# - 如何以编程方式从远程共享点服务器 checkout 文档 (c#)

javascript - Sharepoint-2013 用活跃用户部门填充字段

javascript - 如何调用确认弹出框?

javascript - 获取以像素为单位的返回数据表的大小

javascript - undefined 不是一个对象(评估 this.state),但在我的方法调用中添加了 bind(this)

ruby - REST - 如果只有一个结果,我是将它作为一个对象还是作为一个元素的数组来提供?

Java Spring JSON解析错误: Cannot deserialize instance out of START_ARRAY token