删除所有列表项Sharepoint 2013 REST

时间:2014-03-19 15:52:13

标签: rest sharepoint sharepoint-2013 http-delete

我需要使用REST API删除Sharepoint列表中的所有项目。
我怎样才能做到这一点?
我可以使用以下方法删除单个项目: " / _ AP​​I /网络/列表/ getByTitle(' MYLIST')/项目(' ID')"

我尝试删除ID,但它无效。

3 个答案:

答案 0 :(得分:4)

你可以试试这个

function deleteItem(url) {
$.ajax({
    url: _spPageContextInfo.webAbsoluteUrl + url,
    type: "DELETE",
    headers: {
        "accept": "application/json;odata=verbose",
        "X-RequestDigest": $("#__REQUESTDIGEST").val(),
        "If-Match": "*"
    },
    success: function (data) {

    },
    error: function (error) {
        alert(JSON.stringify(error));
    }
});
}

$.ajax({
    url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('MyList')/items",
    type: "GET",
    headers: {
        "accept": "application/json;odata=verbose",
    },
    success: function (data) {
        var items = data.d.results;
        for(var item in items){
            var url = "/_api/Web/Lists/getByTitle('MyList')/getItemById(item.ID)"
            deleteItem(url);
        }
    },
    error: function (error) {
        alert(JSON.stringify(error));
    }
});

答案 1 :(得分:2)

您必须使用上面显示的URI为列表中的每个项目进行一次删除调用,然后连续传入每个ID。如果列表中有很多项目,那么删除它可能会更便宜,更快,然后重新创建列表本身。

答案 2 :(得分:0)

您可以尝试使用此代码。但是你应该知道,这可能是你的清单中的例外情况。使用此代码后,我遇到了列表问题。我删除了所有项目,但我的ListCount属性设置为-3。我建议使用批处理请求来形成和执行请求。它会更快更安全

window.I = 0;
deleteFunction();

function deleteListItem(listTitle, listItemId, type)
{
    try
    {
    var listItemUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/items(" + listItemId + ")";
    var itemPayload = {'__metadata': {'type': type}};

    $.ajax({       
       url: listItemUri,
       type: "POST",   
       contentType: "application/json;odata=verbose",
       headers: { 
          "Accept": "application/json;odata=verbose",
          "X-RequestDigest" : $("#__REQUESTDIGEST").val(),
          "X-HTTP-Method": "DELETE",
          "If-Match": "*"
       },success :function(){
           console.log("deleted " + window.I);
           window.I++; 
           deleteFunction();
           },
           error: function (data) {
           window.I++; 
           deleteFunction();
          }
    });
    }
    catch(e)
    {
        console.log("error" + window.I);
        window.I++;
    }
}

function deleteFunction()
{
    try
    {
        if(window.I > 1000) return;
        deleteListItem('ListName',window.I,'SP.Data.ListNameListItem');
        console.log("deleted " + window.I);
    }
    catch(e)
    {
        console.log("error" + window.I);
        window.I++;
    }
} 
相关问题