在SharePoint Online中未定义SP.ClientContext

时间:2018-07-11 16:08:52

标签: jquery sharepoint sharepoint-online sharepoint-jsom

我正在尝试通过SharePoint Online中的JSOM获取登录用户的详细信息。

下面是我正在尝试的代码:

SP.SOD.registerSod('sp.js', "/_layouts/15/sp.js");
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getCurrentUser);

function getCurrentUser() {
    try {
        var clientContext = new SP.ClientContext.get_current();
        var tempcurrentUser = clientContext.get_web().get_currentUser();
        clientContext.load(tempcurrentUser);
        clientContext.executeQueryAsync(function () {
            prf.loggedUser = tempcurrentUser.get_id();
            var userAcc = tempcurrentUser.get_loginName();                
        }, queryFailure);
    }
    catch (err) {
        queryFailure();
    }
}

function queryFailure() {
    alert('Error while accessing Active Directory');
}

在上面的代码中,当我尝试访问 SP.ClientContext.get_current() 时,我收到错误消息,指出未定义SP.ClientContext。

我是SharePoint Online的新手,这个问题听起来很简单,但我愿意学习。

注意:上面的代码在SharePoint 2013中可以正常工作。

3 个答案:

答案 0 :(得分:1)

要在线获取SharePoint中的用户信息,无需编写代码。您可以使用 Microsoft提供的现有 _spPageContextInfo

输出代码:

enter image description here

答案 1 :(得分:0)

尝试使用

代替使用SP.SOD.executeFunc

“ executeOrDelayUntilScriptLoaded”

https://docs.microsoft.com/en-us/previous-versions/office/developer/sharepoint-2010/ff411788(v%3doffice.14)

答案 2 :(得分:0)

在SharePoint Online中,建议您使用REST API和jQuery Ajax来实现它。

<script src="https://code.jquery.com/jquery-1.12.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/CurrentUser",
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose"},
        async:false,
        success: function (data) {
            var userId=data.d.Id;
            var loginName=data.d.LoginName;
            alert("UserId:"+userId+"  LoginName:"+loginName);
        },
        error: function (err) {
            console.log(err);
        }
    });
});
</script>

如果您想获取当前的用户个人资料信息,我们可以使用下面的REST API。

https://siteurl/_api/SP.UserProfiles.PeopleManager/GetMyProperties

参考:SharePoint 2013: Get UserProfile Properties with REST API

相关问题