北城已荒凉 2016-12-23 06:25 采纳率: 0%
浏览 40

AJAX不返回对象

I am using AJAX GET to get a local JSON file and it does that, but once i try to return it says undefined.

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条回答 默认 最新

  • MAO-EYE 2016-12-23 06:30
    关注

    Just implement a callback for response, something like this

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

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?