gpt4 book ai didi

javascript - AJAX 不返回对象

转载 作者:行者123 更新时间:2023-12-03 05:22:54 25 4
gpt4 key购买 nike

我正在使用 AJAX GET 获取本地 JSON 文件,它确实做到了这一点,但一旦我尝试返回,它就会显示未定义。

ScoreHandler = function () {
this.getScores = function() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(this.responseText);
//This logs object
console.log(data);
return data;
}
};
xmlhttp.open("GET", "JSON/Scores.json", true);
xmlhttp.send();
};
};

HighScores = function (scoreHandler) {

var scoreHandler = scoreHandler;
var scores = this.scoreHandler.getScores();
//This logs undefined
console.log(scores);
}

最佳答案

只需实现响应的回调,如下所示

ScoreHandler = function () {
this.getScores = function(callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(this.responseText);
//This logs object
console.log(data);
if(typeof callback === 'function')
callback(data);
//return data;
}
};
xmlhttp.open("GET", "JSON/Scores.json", true);
xmlhttp.send();
};
};

HighScores = function (scoreHandler) {

var scoreHandler = scoreHandler; //why this line use it directly
var scores = this.scoreHandler.getScores(function(data){
console.log("response", data); //you can see the data here
});
//This logs undefined
console.log(scores);
}

关于javascript - AJAX 不返回对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41296222/

25 4 0
文章推荐: javascript - 当在单独的