san*_*oco 1 ajax rest sharepoint json sharepoint-2013
我正在尝试通过REST API自动确保某些用户。我的REST电话:
$.ajax({
url: "blablabla/_api/web/ensureuser",
type: "POST",
data: "{ 'logonName': 'i%3A0%23.w%7Cdomain%09logonName' }",
headers: {
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"accept": "application/json;odata=verbose"
},
success: function () {
console.log("done!");
},
error: function (err) {
console.log(JSON.stringify(err));
}
});
Run Code Online (Sandbox Code Playgroud)
现在,在发送此呼叫时,出现以下错误;
“错误的请求:Microsoft.Data.OData.ODataContentTypeException找不到与响应的内容类型匹配的受支持的MIME类型。所有受支持的类型'application / json; odata = verbose'与内容类型都不匹配' application / x-www-form-urlencoded; charset = UTF-8'“
发生此错误是因为ContentType这是JSON请求,因此需要明确指定:
contentType(预设值:'application / x-www-form-urlencoded; charset = UTF-8')将数据发送到服务器时,请使用此内容类型。默认值为“ application / x-www-form-urlencoded; charset = UTF-8”
例
function ensureUser(webUrl,loginName)
{
var payload = { 'logonName': loginName };
return $.ajax({
url: webUrl + "/_api/web/ensureuser",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(payload),
headers: {
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"accept": "application/json;odata=verbose"
}
});
}
var loginName = 'i:0#.f|membership|jdoe@contoso.onmicrosoft.com'
ensureUser(_spPageContextInfo.webAbsoluteUrl,loginName)
.done(function(data)
{
console.log('User has been added');
})
.fail(function(error){
console.log('An error occured while adding user');
});
Run Code Online (Sandbox Code Playgroud)