Javascript JS和jQuery,当函数完成时,全局对象变为空
我有一个对象问题dict。当接收到json数据时,程序调用LoadDict()函数,其中dict对象被来自服务器的新数据填充。我使用FireBug来确保dict包含所有具有正确信息的新元素,但当函数完成时,dict再次变为空,就像ajax请求之前一样。此代码在全局范围内执行:Javascript JS和jQuery,当函数完成时,全局对象变为空,javascript,jquery,json,scope,javascript-objects,Javascript,Jquery,Json,Scope,Javascript Objects,我有一个对象问题dict。当接收到json数据时,程序调用LoadDict()函数,其中dict对象被来自服务器的新数据填充。我使用FireBug来确保dict包含所有具有正确信息的新元素,但当函数完成时,dict再次变为空,就像ajax请求之前一样。此代码在全局范围内执行: var dict = new Dictionary(); function LoadDict(words) { for (var i in words) { var word = new Word(
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);
这是我字典课的一些代码
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);
}
函数字典(){
this.collection=新数组();
此值为0.count;
this.sorted=false;
}
Dictionary.prototype.Add=函数(word){
if(word的word实例){
word.id=this.count;
this.collection[this.count]=word;
这个.count++;
this.sorted=false;
}
}
Dictionary.prototype.PrintDictionary=函数(){
函数WordToString(word){
var line=“”+word.word+”[“+word.transcript+”]-“+word.means[0];
for(var j=1;j”+WordToString(this.collection[i])+“”;
结果+=“”
记录(结果);
}
Dictionary类的声明在创建dict对象之前进行。
救命啊 时间问题
在代码中,
PrintDictionary
函数在ajax调用完成之前已经执行。问题在于$.getJSON
是异步的
这意味着
dict.printdiction()代码>行在之前执行结果从
getJSON调用返回可能是您的cantry it sync调用