我有以下代码,它将返回当前登录的 SharePoint 用户的登录名:
var currentUser;
var currentUserName;
ExecuteOrDelayUntilScriptLoaded(MainMethod,'sp.js');
function MainMethod() {
GetName();
alert("MAIN " + currentUserName);
}
function GetName(){
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() {
currentUserName= currentUser.get_loginName().split("\\")[1];
alert("GetName " + currentUserName);
}
function onQueryFailed(sender, args) {
alert('Failed to retrieve user name');
}
当我运行代码时,我收到这 2 个警报消息框:
“GetName”名字.姓氏
“MAIN”未定义
行 currentUserName= currentUser.get_loginName().split("\\")[1];
不应该将 firstname.lastname
值分配给全局currentUserName
变量?
最佳答案
您可以使用 window.currentUserName = currentUser.get_loginName().split("\\")[1]
确保您正在访问全局属性。
为了避免许多变量污染全局命名空间,您可以将它们分组在一个对象中,如下所示:
window.user = {
currentUserName,
currentUser
}
然后您可以通过window.user.currentUserName
访问它。
关于JavaScript 未分配给全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37613824/