简体   繁体   中英

How to update a record within a sharepoint list using Sharepoint REST API, with jQuery?

I would like to update a field within a record of a sharepoint list with a new value utilizing the Sharepoint REST API and jQuery.

The item I have has an id of 123 and

I have the following dictionary object and I would like to update the record's field called 'example_field' with the value of 'example_text'

var example_dictionary_object = {example_field:'example_text',id:123}

I have tried the below based on this stickoverflow question with no luck:

function sharepoint_record_field_update(list_name,dictionary_object,id){
    var appWebUrl = _spPageContextInfo.webAbsoluteUrl;
    $.ajax({
        url: appWebUrl + "/_api/web/lists/getbyTitle('" + list_name + "')/items"+"(" + id + ")",
        type: "POST",
        data: JSON.stringify(dictionary_object),
        async: false,
        headers: {
            "accept": "application/json;odata=verbose"
        },
        success: function (data) {
            console.log('Item has been updated');
        },
        error: function (err) {
            console.log(err);
        }
    });
}


sharepoint_record_field_update('example_list',{example_field:'example_text'},123)

You are not using it correctly. You are missing ListItemEntityTypeFullName as well as couple of headers necessary like request digest, x-http-method and if-match.

Try and modify your code from below sample code:

function UpdateListItem(){
    var listName="CustomList";
    var listItemId=123;
    var itemType = GetItemTypeForListName(listName);
    var item = {
        "__metadata": { "type": itemType },
        "Title": "value change"    
    };

    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items("+listItemId+")",
        type: "POST",
        contentType: "application/json;odata=verbose",
        data: JSON.stringify(item),
        headers: {
            "Accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "X-HTTP-Method": "MERGE",
            "If-Match": "*"
        },
        success: function (data) {
            console.log('Success');            
        },
        error: function (data) {
            console.log("Error");
        }
    });
}

function GetItemTypeForListName(name) {
    return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}    

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