SharePoint 2013 get current user using JavaScript

前端 未结 11 2367
挽巷
挽巷 2020-12-13 09:32

How to get current user name using JavaScript in Script Editor web part?

相关标签:
11条回答
  • 2020-12-13 09:51

    To get current user info:

    jQuery.ajax({
        url: _spPageContextInfo.webServerRelativeUrl + "/_api/web/currentuser",
        type: "GET",
        headers: { "Accept": "application/json;odata=verbose" }
    }).done(function( data ){
        console.log( data );
        console.log( data.d.Title );
    }).fail(function(){
        console.log( failed );
    });
    
    0 讨论(0)
  • 2020-12-13 09:53

    I found a much easier way, it doesn't even use SP.UserProfiles.js. I don't know if it applies to each one's particular case, but definitely worth sharing.

    //assume we have a client context called context.
    var web = context.get_web();
    var user = web.get_currentUser(); //must load this to access info.
    context.load(user);
    context.executeQueryAsync(function(){
        alert("User is: " + user.get_title()); //there is also id, email, so this is pretty useful.
    }, function(){alert(":(");});
    

    Anyways, thanks to your answers, I got to mingle a bit with UserProfiles, even though it is not really necessary for my case.

    0 讨论(0)
  • 2020-12-13 09:54

    you can use below function if you know the id of the user:

    function getUser(id){
    var returnValue;
    jQuery.ajax({
     url: "http://YourSite/_api/Web/GetUserById(" + id + ")",
     type: "GET",
     headers: { "Accept": "application/json;odata=verbose" },
     success: function(data) {
           var dataResults = data.d;
           alert(dataResults.Title);
      }
    });
    }
    

    or you can try

    var listURL = _spPageContextInfo.webAbsoluteUrl + "/_api/web/currentuser";
    
    0 讨论(0)
  • 2020-12-13 09:56

    try this code..

    function GetCurrentUsers() {
    
        var context = new SP.ClientContext.get_current();
        this.website = context.get_web();
        var currentUser = website.get_currentUser();
        context.load(currentUser);
        context.executeQueryAsync(Function.createDelegate(this, onQuerySucceeded), Function.createDelegate(this, onQueryFailed));
       function onQuerySucceeded() {
    
           var currentUsers = currentUser.get_title();
           document.getElementById("txtIssued").innerHTML = currentUsers;
    
        }
    
        function onQueryFailed(sender, args) {
            alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
        }   
    

    }

    0 讨论(0)
  • 2020-12-13 09:57

    You can use sp page context info:

    _spPageContextOnfo.userLoginName

    0 讨论(0)
  • 2020-12-13 09:58

    If you are in a SharePoint Page just use:

    _spPageContextInfo.userId;
    
    0 讨论(0)
提交回复
热议问题