最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Getting the current user in SharePoint2010 Client OMECMAScript - Stack Overflow

programmeradmin4浏览0评论

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?

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?

Share Improve this question asked Nov 24, 2010 at 9:52 user4531user4531 2,5658 gold badges30 silver badges38 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

Here is a more plete 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

发布评论

评论列表(0)

  1. 暂无评论