我有以下api从http://starlord.hackerearth.com/gamesarena获取数据 我正在尝试使用以下代码访问json:
<!DOCTYPE html>
<html>
<body>
<h2>Use the XMLHttpRequest to get the content of a file.</h2>
<p>The content is written in JSON format, and can easily be converted into a JavaScript object.</p>
<p id="demo"></p>
<script>
var requestURL = 'http://starlord.hackerearth.com/gamesarena';
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
var superHeroes = request.response;
console.log(request.response);
</script>
</body>
</html>
我希望看到JSON数据,但是得到null。可以解释缺少的内容
答案 0 :(得分:2)
嗯,那是因为你在响应来之前试图获取内容。默认情况下,所有XMLHttpRequests都是异步的(很多浏览器都不会让你发出同步请求)。您可以像这样以异步方式获取响应内容:
var requestURL = 'http://starlord.hackerearth.com/gamesarena';
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if(request.readyState === XMLHttpRequest.DONE) {
// response
console.log(request.response);
}
};
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
答案 1 :(得分:0)
您必须使用load
事件来处理服务器响应:
request.addEventListener("load", function(){
console.log(this.responseText);
});
请注意,load
事件仅在服务器向客户端发送响应时触发。
示例:
<!DOCTYPE html>
<html>
<body>
<h2>Use the XMLHttpRequest to get the content of a file.</h2>
<p>The content is written in JSON format, and can easily be converted into a JavaScript object.</p>
<p id="demo"></p>
<script>
var requestURL = 'http://starlord.hackerearth.com/gamesarena';
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.addEventListener("load", function(){
console.log(this.responseText);
});
request.send();
</script>
</body>
</html>
&#13;