全局变量未定义[重复]

时间:2022-11-05 19:41:23

This question already has an answer here:

这个问题在这里已有答案:

I have a function (all of the unrelated parts of been omitted) that defines a global variable window.playerLibrary. When I check window.playerLibrary in the function itself (`var check #1 I get a value. If I check it just outside of the ajax call it is undefined. If I check it after calling the function, it is undefined:

我有一个函数(省略了所有不相关的部分),它定义了一个全局变量window.playerLibrary。当我在函数本身检查window.playerLibrary时(`var check#1我得到一个值。如果我在ajax调用之外检查它是未定义的。如果我在调用函数后检查它,它是未定义的:

function generateAllCards() {
    $.ajax({
        type: "POST",
        url: "processGame",
        data: {
            mode: "generateCards"
        },
        dataType: "JSON",
        success: function(data) {
            window.playerLibrary = data.playerLibrary;

        // var check #1
            console.log(window.playerLibrary);
        }
    });

// var check #2
    console.log(window.playerLibrary);
}

generateAllCards();
// var check #3
    console.log(window.playerLibrary);

As I'm typing this I suspect the cause is that, since it is defined in an ajax call, var checks #2 and #3 are happening sequentially while var check #1 is happening along side of them and therefore the definition of the variable is not being captured.

当我输入这个时,我怀疑原因是,因为它是在ajax调用中定义的,var检查#2和#3是顺序发生的,而var check#1正在它们旁边发生,因此变量的定义没被捕获。

If this is accurate, is there a way to fix this?

如果这是准确的,有没有办法解决这个问题?

1 个解决方案

#1


0  

Do what you need to do with the playerlibrary inside the success callback, or call a function from there once you know the value has been assigned

在成功回调中执行您需要处理的播放器库,或者在知道已分配值后从该处调用函数

#1


0  

Do what you need to do with the playerlibrary inside the success callback, or call a function from there once you know the value has been assigned

在成功回调中执行您需要处理的播放器库,或者在知道已分配值后从该处调用函数