所以我一直在做一个迷你项目,但是我似乎不能从JavaScript中的JSON文件中获取数据。
我在控制台中显示了数据,但是如果我想打印出第一个数组,我得到的值是'undefined‘
这是我的script.js文件:
var URL = "https://api.themoviedb.org/3/movie/popular?api_key=f1d314280284e94ff7d1feeed7d44fdf&language=en-US&page=1";
var ourRequest = new XMLHttpRequest;
ourRequest.open('GET', URL);
ourRequest.onload = function (){
var data = ourRequest.responseText;
var ourData=JSON.parse(data);
console.log(ourData); // this line of code displays the full list of movies
console.log(ourData[0]); // this line displays undefined
发布于 2018-08-15 08:50:42
你可以使用我写的这个函数。它用于我的挖掘池上的图形,因此您可以在metaverse.farm上看到它的实际效果。如果不成功,它将每10秒自动重试一次。
function getJsonData(url, callback) {
let request = new XMLHttpRequest;
let timer = setTimeout(function() {
getJsonData(url, callback);
}, 10000);
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status === 200) {
clearTimeout(timer);
return callback(JSON.parse(request.responseText));
}
}
request.open('GET', url);
request.send();
}
就这么叫吧:
var jsonUrl = "https://api.themoviedb.org/3/movie/popular?api_key=f1d314280284e94ff7d1feeed7d44fdf&language=en-US&page=1";
var myData;
getJsonData(jsonUrl, function(data) {
myData = data;
});
然后你所需要的就是:
console.log(myData.results[0]);
输出:
{vote_count: 7552, id: 299536, video: false, vote_average: 8.3, title: "Avengers: Infinity War", …}
你甚至可以这样做:
var jsonUrl = "https://api.themoviedb.org/3/movie/popular?api_key=f1d314280284e94ff7d1feeed7d44fdf&language=en-US&page=1";
getJsonData(jsonUrl, function(data) {
data.results[0].title = "WOOOOOOOOHOOOOOOOO!";
console.log(data.results[0]);
});
输出:
{vote_count: 7552, id: 299536, video: false, vote_average: 8.3, title: "WOOOOOOOOHOOOOOOOO!", …}
如果你把它和像这样的函数结合起来,你就有了一个异步JSON加载器,它不会阻止浏览器做其他事情:
var myData;
loader = $('.loader');
async function refreshData() {
loader.show();
return new Promise(function(resolve, reject) {
getJsonData(jsonUrl, function(data) {
// Once the data is loaded...
myData = data;
insertData();
loader.hide();
});
});
}
https://stackoverflow.com/questions/51851391
复制相似问题