简体   繁体   中英

Delete item from SharePoint List using JavaScript and REST

I have some JavaScript (physical file located in /SiteAssets library) that should delete an item in a SharePoint list.

We have existing JavaScript code that retrieves data from the list - it looks like this:

(notice that since the JavaScript runs on a PDP in context of the current user, we don't need a specific access token for the request)

var data = $.ajax({
    url: projSiteUrl + "/_api/lists/getbytitle('<listname>')/items,
    type: "GET",
    dataType: "json",
    async: false,
    headers: {
        Accept: "application/json;odata=verbose"  
    }       
});

So I thought that I could write similar code to delete an item from the list again. I read on https://msdn.microsoft.com/en-us/library/office/jj164022.aspx#HTTPOps that the REST endpoint of SharePoint supports the "normal" REST verbs, so I wrote this, using the DELETE HTTP verb.

var restUrl = spSiteUrl + '/_api/web/lists/GetByTitle(\'' + listTitle + '\')/items(' + itemId + ')';
jQuery.ajax({
    url: restUrl,
    type: "DELETE",
    headers: {
        Accept: "application/json;odata=verbose"  
    }       
})

But I am getting a 403 (FORBIDDEN) when requesting.

I guess the question is: Am I wrong in assuming that the DELETE verb is supported?

Thanks :-)

Ok, so apparently I do need the digest when doing modifications - but not for simple data retrieval.

If I change my code to

jQuery.ajax({
    url: restUrl,
    type: "DELETE",
    headers: {
        Accept: "application/json;odata=verbose",
        "X-RequestDigest": $("#__REQUESTDIGEST").val(),
        "IF-MATCH": "*"
    }       
}).

... it works with a simple AJAX request using the REST HTTP verb DELETE :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM