Getting the current user in SharePoint2010 Client OM / ECMAScript
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: 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?Here is a more complete example with 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
});
}
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
精彩评论