javascript - Sharepoint 2013 通过 REST API : Error 403 Forbidden when trying to create item

标签 javascript ajax json rest sharepoint

我正在尝试使用 Sharepoint 2013 上的其余 API 创建一个简单的列表项。 我的代码:

$.ajax({
    url: siteUrl + "/_api/web/lists/getByTitle('internal_Listname')/items",
    type: "POST",
    contentType: "application/json;odata=verbose",
    data: JSON.stringify({
         '__metadata': {
            'type': 'SP.Data.internal_ListnameListItem',
         },
         'K1F1': k1f1Result,
    }),
    headers: {
        "accept": "application/json;odata=verbose",
        "X-RequestDigest": $("#__REQUESTDIGEST").val(),
    },
    success: function (data) {
        console.log("done");
    },
    error: function (err) {
        console.log(JSON.stringify(err));
    }
});

尝试发送数据时出现 403“禁止”错误。

"error":{
   "code":"-2130575251, Microsoft.SharePoint.SPException",
   "message":{
        "lang":"en-US",
        "value":"The security validation for this page is invalid and might be corrupted. Please use your web browser's Back button to try your operation again."
    }
}
  • 我拥有此站点和列表的完全管理员权限。

最佳答案

很可能发生此错误是因为页面上的表单摘要已过期

在这种情况下,您可以通过向 /_api/contextinfo 端点发出 POST 请求来获取新的表单摘要值。

示例

function getFormDigest(webUrl) {
    return $.ajax({
        url: webUrl + "/_api/contextinfo",
        method: "POST",
        headers: { "Accept": "application/json; odata=verbose" }
    });
}


function createListItem(webUrl, listName, itemProperties) {
    return getFormDigest(webUrl).then(function (data) {

        return $.ajax({
            url: webUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",
            type: "POST",
            processData: false,
            contentType: "application/json;odata=verbose",
            data: JSON.stringify(itemProperties),
            headers: {
                "Accept": "application/json;odata=verbose",
                "X-RequestDigest": data.d.GetContextWebInformation.FormDigestValue
            }
        });
    });
}

用法

//Create a Task item
var taskProperties = {
    '__metadata': { 'type': 'SP.Data.WorkflowTasksItem' },
    'Title': 'Order approval'
};

createListItem(_spPageContextInfo.webAbsoluteUrl, 'Workflow Tasks', taskProperties)
.done(function (data) {
    console.log('Task has been created successfully');
})
.fail(function (error) {
    console.log(JSON.stringify(error));
});

关于javascript - Sharepoint 2013 通过 REST API : Error 403 Forbidden when trying to create item,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32435432/

相关文章:

javascript - 在不修改递归函数的情况下添加延迟

javascript - 即使智能手机屏幕关闭,也会在后台运行 Web 应用程序

javascript - 如何检查ajax响应中的选项?

python - 使用 py2exe 打包时不包含 key 环模块

javascript - Angular js渲染速度[慢]阻止加载程序显示

JavaScript : Why typeof() is returing boolean value as a string?

javascript - 在全局范围内扩展 jQuery ajax 的成功

php - 从数据库加载数据 + ajax + php

json - 在 RethinkDB 中使用 .lt() 和 .filter() 的二级索引

python - 修复几乎有效的 JSON 文件