AJAX不返回对象

时间:2016-12-23 06:25:24

标签: javascript json ajax

我正在使用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); 
}

1 个答案:

答案 0 :(得分:1)

只需实现response的回调,就像这样

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); 
}