2016-12-23 3 views
0

Ich benutze AJAX GET, um eine lokale JSON-Datei zu bekommen, und es tut das, aber wenn ich versuche, es zurückzugeben, sagt es undefined.AJAX gibt kein Objekt zurück

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

Sie keine Daten von einem 'async' zurückrufen kann. Verwenden Sie stattdessen 'callbakcs', um diese Antwort zu verwenden. –

+0

können Sie ein Versprechen verwenden? –

+0

undefiniert, weil es asynchron gehandhabt wird. Es wird also einige Zeit brauchen, um die Daten zurückzugeben. – Ninjaneer

Antwort

1

implementieren Sie einfach einen Rückruf für response, so etwas wie dieses

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

Danke funktioniert jetzt wie ein Charme. – iWillBeMaster

+0

Ich bin froh, das hat dir geholfen :). –

Verwandte Themen