Javascript 在 SharePoint2010 Client OM / ECMAScript 中获取当前用户
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4265429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting the current user in SharePoint2010 Client OM / ECMAScript
提问by user4531
Hallo,
你好,
i would like to do something that i thought would be fairly simple:
get the loginName of the current user using the SharePoint2010 Client OM with ECMAScript.
Here is my code:
我想做一些我认为相当简单的事情:
使用带有 ECMAScript 的 SharePoint2010 客户端 OM 获取当前用户的登录名。
这是我的代码:
var currentcontext = new SP.ClientContext.get_current();
var currentweb = currentcontext.get_web();
currentcontext.load(currentweb);
var currentuser = currentweb.get_currentUser();
currentcontext.load(currentuser);
var loginName = currentuser.get_loginName();
the last line throws an exception:
"The property or field has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested."
But why? I've loaded the 'currentuser', so why is the 'property or field' not initialized?
最后一行抛出异常:“属性或字段尚未初始化。尚未请求或尚未执行请求。可能需要显式请求。”
但为什么?我已经加载了“currentuser”,为什么“属性或字段”没有初始化?
回答by Anatoly Mironov
Here is a more complete example with executeQueryAsync:
这是一个更完整的 executeQueryAsync 示例:
SP.SOD.executeOrDelayUntilScriptLoaded(runMyCode, "SP.js");
function runMyCode() {
var ctx = new SP.ClientContext.get_current();
var web = ctx.get_web();
ctx.load(web);
var user = web.get_currentUser();
user.retrieve();
ctx.executeQueryAsync(
function () {
//only in the success case you can work with user login
doSomethingWithUserLogin(user.get_loginName());
},
function (data) {
//notify the failure
});
}
回答by Dennis G
You need to retrieve the user first and load the web, not the user.
您需要先检索用户并加载网络,而不是用户。
The following should work:
以下应该工作:
var currentcontext = new SP.ClientContext.get_current();
var currentweb = currentcontext.get_web();
currentcontext.load(currentweb);
var currentuser = currentweb.get_currentUser();
currentuser.retrieve();
currentcontext.load(currentweb);
var loginName = currentuser.get_loginName();
For an even better example using an asynchronous query check the following tutorial: SharePoint 2010 ECMAScript - How to know logged in user information
有关使用异步查询的更好示例,请查看以下教程: SharePoint 2010 ECMAScript - 如何知道登录的用户信息