为什么我的函数返回“未定义”?

时间:2019-06-15 00:01:22

标签: javascript rest sharepoint

相对newb在这里。我想使用一个函数来获取带有REST的用户ID(这在SharePoint 2013中),然后可以将其用作另一个函数中的变量值。当我发出警报或控制台日志并使用硬编码的用户ID直接登录我的函数时,该函数将起作用。当我尝试按以下方式使用它时,它会在我的click事件中返回“ undefined”。我现在查看了许多答案,并尝试在代码的开头声明我的“ GetUserIdFromUserName”函数为变量,但这似乎不起作用。

//function i'm trying to get the return data from
    function GetUserIdFromUserName () {
        var siteUrl = _spPageContextInfo.siteAbsoluteUrl;
        $.ajax({
            url: siteUrl + "/_api/web/siteusers(@v)?@v='i:0e.t|vds|d4td6725-9f3a-e711-9067-006345ba12ca'",
            method: "GET",
            headers: { "Accept": "application/json; odata=verbose" },
            success: function (data) {
                //alert(JSON.stringify(data.d.Id));
                return JSON.stringify(data.d.Id);
                //console.log(JSON.stringify(data.d.Id));
            },
            error: function (data) {
                console.log(JSON.stringify(data));
            }
        });
    }

    //click event to create new items
    $("body").on("click",".restbutton input",function(){
        var $this = $(this);
        var title = $("input[title='Project']").val();
        var userid = (GetUserIdFromUserName('i:0e.t|vds|d6gb7825-9f3a-b761-9067-005056ba12ca'));
        $(".newLine").each(function(){
            var itemProps = {
                '__metadata': { 'type': 'SP.Data.myListListItem' },
                'Title': title,
                'RequestType': rt,
                'RequestorId':userid
            };  
            createListItem(_spPageContextInfo.webAbsoluteUrl, 'myList', itemProps)
        });
    });

    //my functions to create new list items with REST
    function createListItem(webUrl, listName, itemProps) {
        return getFormDigest(webUrl).then(function (data) {
            return $.ajax({
                url: webUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",
                type: "POST",
                processData: false,
                contentType: "application/json;odata=verbose",
                data: JSON.stringify(itemProps),
                headers: {
                    "Accept": "application/json;odata=verbose",
                    "X-RequestDigest": data.d.GetContextWebInformation.FormDigestValue
                },
                success: function(){
                    alert("It worked")
                },
                error: function(){
                    alert("Did not work")
                }
            });
        });
    }

    function getFormDigest(webUrl) {
        return $.ajax({
            url: "https://myURL",
            method: "POST",
            headers: { "Accept": "application/json; odata=verbose" }
        });
    }

0 个答案:

没有答案