调用http://starlord.hackerearth.com/gamesarena API返回null,求排查缺失环节
为什么XMLHttpRequest请求API返回null?
嘿,这个问题我熟!你遇到的核心问题是XMLHttpRequest是异步操作——当你调用request.send()后,浏览器会在后台发送请求,不会阻塞后续代码执行。你现在的代码在send()之后立刻就去读取request.response,这时候请求还没完成,服务器的响应还没回来,所以自然拿到的是null。
修复方案:监听请求完成事件
你需要通过onload事件(或者onreadystatechange)来监听请求的完成状态,只有当请求成功完成后,再去读取响应数据。修改后的代码如下:
<!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.onload = function() { if (request.status >= 200 && request.status < 300) { // 请求成功,处理响应数据 var superHeroes = request.response; console.log(superHeroes); // 可以在这里把数据渲染到页面,比如: document.getElementById('demo').textContent = JSON.stringify(superHeroes); } else { // 请求失败,处理错误 console.error('请求失败,状态码:', request.status); } }; // 监听请求错误 request.onerror = function() { console.error('请求发生网络错误'); }; request.send(); </script> </body> </html>
额外推荐:使用更现代的Fetch API
现在更推荐使用fetch()来发送网络请求,它基于Promise,语法更简洁直观,处理异步逻辑更清晰。给你一个用Fetch实现的例子:
<!DOCTYPE html> <html> <body> <h2>Use Fetch to get JSON data</h2> <p>The content is written in JSON format.</p> <p id="demo"></p> <script> const requestURL = 'http://starlord.hackerearth.com/gamesarena'; fetch(requestURL) .then(response => { if (!response.ok) { throw new Error('网络响应异常'); } return response.json(); }) .then(data => { console.log(data); document.getElementById('demo').textContent = JSON.stringify(data); }) .catch(error => { console.error('请求出错:', error); }); </script> </body> </html>
这样修改后,你就能正常获取到API返回的JSON数据啦!
内容的提问来源于stack exchange,提问作者leo
相关产品推荐
相关产品推荐

