简体   繁体   English

AJAX不返回对象

[英]AJAX does not return object

I am using AJAX GET to get a local JSON file and it does that, but once i try to return it says undefined. 我正在使用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); 
}

Just implement a callback for response , something like this 只需实现一个用于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); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM