【问题标题】:JS and jQuery, global object gets empty when function is finishedJS和jQuery,函数完成时全局对象为空
【发布时间】:2014-08-01 04:23:56
【问题描述】:

我对对象 dict 有疑问。当接收到 json 数据时,程序会调用 LoadDict() 函数,其中 dict 对象会被来自服务器的新数据填充。我使用 FireBug 来确保 dict 包含具有正确信息的所有新元素,但是当函数完成时,dict 再次变为空,就像在 ajax 请求之前一样。此代码在全局范围内执行:

var dict = new Dictionary();
function LoadDict(words) {
    for (var i in words) {
        var word = new Word();
        word.word = words[i].Word;
        word.transcript = words[i].Transcript;
        word.frequency = words[i].Frequency;
        word.meanings = words[i].Meanings;
        word.examples = words[i].Examples;
        word.imgLinks = words[i].ImgLinks;
        dict.Add(word);
    }
}
$.getJSON("getall").done(LoadDict);
dict.PrintDictionary);

这是我的 Dictionary 类的一些代码

function Dictionary() {
    this.collection = new Array();
    this.count = 0;
    this.sorted = false;
}

Dictionary.prototype.Add = function(word) {
    if (word instanceof Word) {
        word.id = this.count;
        this.collection[this.count] = word;
        this.count++;
        this.sorted = false;
    }
}
Dictionary.prototype.PrintDictionary = function() { 
    function WordToString(word) {
        var line = "<strong>" + word.word + "</strong> [" + word.transcript + "] - " + word.meanings[0];
        for (var j = 1; j < word.meanings.length; j++) {
            line += ", " + word.meanings[j];
        }
        return line;
    }
    var result = "<ol>"
    for (var i = 0; i < this.collection.length; i++)
        result += "<li>" + WordToString(this.collection[i]) + "</li>";
    result += "</ol>"
    document.write(result);
}

Dictionary 类的声明在创建 dict 对象之前进行。 请帮忙!

【问题讨论】:

  • 也许你可以试试同步调用

标签: javascript jquery json scope javascript-objects


【解决方案1】:

时间问题。

在您的代码中,PrintDictionary 函数在 ajax 调用完成之前已执行。

【讨论】:

    【解决方案2】:

    问题在于$.getJSON 是异步的。

    这意味着dict.PrintDictionary(); 行被执行结果从getJSON 调用返回

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-13
      • 2023-03-25
      • 1970-01-01
      相关资源
      最近更新 更多