ReferenceError: _spPageContextInfo is not defined

ReferenceError: _spPageContextInfo is not defined

我的 js 文件中有以下代码:

var configNews = {
    url:_spPageContextInfo.webAbsoluteUrl,
    newsLibrary: 'DEMONews',
    listId: ''
};

// Getting the ListID
$.ajax({
    url: configNews.url + "/_api/web/lists/getbytitle('" + configNews.newsLibrary + "')?$select=Id",
    method: "GET",
    headers: { "Accept": "application/json; odata=verbose" },
    success: function (data) {
        // Returning the results
        configNews.listId = data.d.Id;
    },
    error: function (data) {
        alert(data);
    }
});

但是我收到以下错误: ReferenceError: _spPageContextInfo 未定义 我不知道我错在哪里以及如何消除这个错误

代码正确。但不要在页面加载前尝试 运行 它。 _spPageContextInfo 在主体部分的某处定义。所以,它在头部部分不可用。

只需尝试 运行 您的代码 DOM 就绪,或者将其放在页面末尾。

因为它是共享点代码,请尝试 运行 这个:

SP.SOD.executeFunc("SP.js","ClientContext",functionName)

这确保加载包含指定函数 (ClientContext) 的指定文件 (sp.js),然后运行指定的回调函数名称。

意识到 SharePoints _spPageContextInfo 在它被自动初始化之前正在被使用