如何用Chart.js读取外部JSON统计动漫喜剧/奇幻品类数量并生成图表
Fixing Your Empty Anime Genre Chart
Hey there, let's get that bar chart working properly—you've got a couple of key issues in your code, mostly around asynchronous data loading and small typos. Here's the breakdown and corrected implementation:
Key Issues in Your Original Code
- Asynchronous Data Loading:
$.getJSONruns in the background, so your loop and chart setup code executes before the JSON data finishes loading. At that point,datais stillundefined, so no counts get calculated. - Variable Typo: You wrote
genress.lengthinstead ofgenres.length(extra 's')—this throws a reference error that stops your count logic. - Mismatched Labels & Variables: Your chart labels reference "Super Natural" but your variable is named
fantasy, and you tried using an undefinedsuperNaturalvariable in the data array.
Corrected Full Code
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> </head> <body> <div class="container"> <canvas id="myChart"></canvas> </div> <script> // Move all logic inside the getJSON callback to ensure data is loaded first $.getJSON("anime.json", function(json) { let comedy = 0; let fantasy = 0; // Iterate over each anime entry for (let i = 0; i < json.length; i++) { const anime = json[i]; // Skip if genres don't exist to avoid errors if (!anime.genres) continue; const genres = anime.genres; for (let j = 0; j < genres.length; j++) { const value = genres[j].trim().toLowerCase(); if (value === 'comedy') { comedy++; } if (value === 'fantasy') { fantasy++; } } } // Initialize the chart now that we have counts const myChart = document.getElementById('myChart').getContext('2d'); new Chart(myChart, { type: 'bar', data: { labels: ['Comedy', 'Fantasy'], // Aligned with our variables datasets: [{ label: 'Anime Count by Genre', data: [comedy, fantasy], // Matched to labels and variables backgroundColor: ['#ffcc00', '#9933ff'], // Optional: add colors for clarity borderColor: ['#cc9900', '#662299'], borderWidth: 1 }] }, options: { scales: { y: { beginAtZero: true, title: { display: true, text: 'Number of Anime' } }, x: { title: { display: true, text: 'Genre' } } } } }); }); </script> </body> </html>
What Changed & Why
- Async Handling: All data processing and chart initialization is now inside the
$.getJSONcallback. This guarantees we only work with the data once it's fully loaded fromanime.json. - Typo Fix: Corrected
genresstogenresso the inner loop can iterate over the genre list. - Label/Variable Alignment: Updated chart labels to match our
comedyandfantasyvariables, and fixed the data array to use the correct variable names. - Error Prevention: Added a check for
anime.genresto skip entries that don't have a genre list (avoids potential errors if your JSON has incomplete entries). - Optional Enhancements: Added basic colors and axis titles to make the chart more readable—feel free to adjust these to your preference.
内容的提问来源于stack exchange,提问作者user13150038




