SharePoint 2013 ClientContext:如何通过MULTIPLE CONDITION过滤器删除特定列表项?

夏期劇*_*期劇場 3 javascript rest sharepoint sharepoint-2013 csom

通过使用SP.ClientContext从Javascript结束,下面是我用来"更新"列表项的代码.只是:

    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);
Run Code Online (Sandbox Code Playgroud)

这允许我通过一个条件查询update列表项,这是:getItemById(itemID)这里.

现在,让我们说,我要删除的项目:

  • 年龄= 30岁
  • 国家=美国

那么我如何使用多个条件进行此类查询.然后甚至要删除吗?


更新


根据下面的答案,我发现与CSOM相比,REST API更容易和更清晰地用于Client/Javascript端.(那么,当然我已经将所有代码都改为REST API方式了.)

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

谢谢!:)

Dan*_*l B 7

这可以通过两种不同的方式完成,可以使用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);
Run Code Online (Sandbox Code Playgroud)

使用SharePoint REST API

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

简单的想法是

  1. 向REST api发出请求并获取与您的过滤条件匹配的所有项目
  2. 对于返回的集合中的每个对象,请创建另一个删除该项的请求,并将请求添加到请求数组中
  3. 完成所有请求后,随心所欲!

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


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!");
    });
});
Run Code Online (Sandbox Code Playgroud)

一些有用的来源

jQuery 使用SharePoint REST api对列表项上的延迟对象CRUD操作