如何使用Javascript

时间:2016-06-02 12:46:21

标签: javascript .net api sharepoint-2013 internet-explorer-11

您好我在Content Editor Web Part中有以下代码,它会检索当前用户的名称并将其显示在消息框中:

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
<script language="javascript" type="text/javascript"> 

function getUser() {
    var userid = _spPageContextInfo.userId;
    //alert(userid);

    var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
    var requestHeaders = { "accept": "application/json;odata=verbose" };
    $.ajax({
        url: requestUri,
        contentType: "application/json;odata=verbose",
        headers: requestHeaders,
        success: onSuccess,
        error: onError
    }); 

    function onSuccess(data, request) {
        var loginName = data.d.Title;
        alert(loginName);
    } 
    function onError(error) {
        alert("Error on retrieving current user.");
    }
}


    $(document).ready(function() {
        getUser();
    });
</script>

我还可以使用alert(data.d.Email);显示电子邮件。

但是,当我尝试调用data.d.Groups时(根据the documentation - 显示存在Groups属性),我看到一个带有[object Object]的消息框。

如何从中检索单个项目(我假设的是)?

我试过了:

var group = data.d.Groups[0];
alert(group);

但这只是undefined

我认为这个对象会包含我的部门我错了吗?

无论哪种方式,有没有办法迭代这些对象,或者我是否正确地完成了但是在空数组上?

谢谢

尝试记录群组

function onSuccess(data, request) {
    var loginName = data.d.Title;
    console.log(loginName);

    var groups = data.d.Groups;
    console.log(groups);
} 

我无法在F12控制台窗口中看到上述任一日志...(Internet Explorer)

尝试2 - 记录成功

使用下面的代码,我能够获得与以前相同的结果,但这次console.log()调用确实有效(仍然不知道为什么以前的调用没有):

ExecuteOrDelayUntilScriptLoaded(init,'sp.js');
var currentUser;
function init(){
    this.clientContext = new SP.ClientContext.get_current();
    this.oWeb = clientContext.get_web();
    currentUser = this.oWeb.get_currentUser();
    this.clientContext.load(currentUser);
    this.clientContext.executeQueryAsync(Function.createDelegate(this,this.onQuerySucceeded), Function.createDelegate(this,this.onQueryFailed));
}

function onQuerySucceeded() {

    var groups = currentUser.get_groups();
    alert(groups);
    console.log(groups);

    var name = currentUser.get_loginName(); 
    alert(name);
    console.log(name);

    var id = currentUser.get_id();
    alert(name);

    var title = currentUser.get_title();
    alert(title);

    var email = currentUser.get_email();
    alert(email);
}

function onQueryFailed(sender, args) {
    alert('Request failed. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}

调用console.log(groups);后,F12控制台中出现以下内容:

enter image description here

2 个答案:

答案 0 :(得分:0)

“data.d.Groups”是对象,当你将它传递给.html(data.d.Groups)时,你将它作为[object Object]得到它,因为对象将转换为字符串Just循环对象和你会得到关键和价值

     for (key in data.d.Groups){
       alert("key: " + key + "value :" + data.d.Groups[key]);
     }

答案 1 :(得分:0)

我能够找到一个相当难看的解决方案,但确实有效。

首先,我们需要在预制中调用一些.js文件

<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.0.min.js"></script>
<script src="/_layouts/15/SP.Runtime.js"></script>
<script src="/_layouts/15/SP.js"></script>
<script src="/_layouts/15/SP.UserProfiles.js"></script>

然后,在<script language="javascript" type="text/javascript">标签内,我们声明了一些全局变量和2个主要函数......

var currentUser;
var currentUserName;
var property = "Department";    

<强> 1。 GetCurrentUserProperty(属性)

此功能实际上只为我们获取当前用户,如果成功,将调用loadUserData(实际上获取我们之前为给定用户定义的property

// This function first gets the current user's firstname.lastname username (e.g. Joe.Bloggs).
// If this is successful, it calls the loadUserData function, which will retrieve the user's
// property which was defined in the global "property" variable.
function GetCurrentUserProperty(){
    this.clientContext = new SP.ClientContext.get_current();
    this.oWeb = clientContext.get_web();
    currentUser = this.oWeb.get_currentUser();
    this.clientContext.load(currentUser);
    this.clientContext.executeQueryAsync(onQueryUserSuccess, onQueryUserFail);
}
function onQueryUserSuccess() {
    // If the query is successful, extract the first.last username and then call loadUserData
    window.currentUserName= currentUser.get_loginName().split("\\")[1]; 
    loadUserData(window.currentUserName);
}
function onQueryUserFail(sender, args) {
    alert('Failed to retrieve user name');
}

<强> 2。 loadUserData

此函数使用给定的user.name并获取该用户存储在property中的属性。在success函数中,我只是将结果输出到alert窗口:

function loadUserData(userName){        
    //Get Current Context   
    var clientContext = new SP.ClientContext.get_current();

    //Get Instance of People Manager Class
    var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);

    //Property to fetch from the User Profile
    var strDepartment = window.property;

    //If you are on On-Premise:
    var targetUser = "BARDOM1\\" + userName;

    //Create new instance of UserProfileProperty
    departmentProperty = peopleManager.getUserProfilePropertyFor(targetUser, strDepartment)

    //Execute the Query. (No load method necessary)
    clientContext.executeQueryAsync(onSuccess, onFail);
}
function onSuccess() {    
    var messageText = window.property + " is " + departmentProperty .get_value();
    alert(messageText);
}
function onFail(sender, args) {
    alert("Error: " + args.get_message());
}

最后,要实际运行此过程,我们需要调用GetCurrentUserProperty();。我将所有这些代码放入一个名为testproperty.js的文件中,并将其保存在SiteAssets中。然后,在我们希望代码运行的页面上,添加Content Editor Web Part并在编辑 - &gt;呼叫路径为../../SiteAssets/testproperty.js。这将在页面加载后运行 - 希望这有助于其他任何可能坚持这一点的人!