I’m trying to show JSON data in a div after a JSONP request. My code gets the data fine, but I can’t figure out how to display it nicely. Here’s what I’ve got so far:
$.ajax({
url: 'some_api_url',
type: 'GET',
dataType: 'jsonp',
success: function(data) {
$('#results').html(data.query.scores);
console.log(data);
}
});
The console.log works, but data.query.scores
just shows up as undefined in the div. I want to show the home team, away team, and score for each game. Something like:
Team A - Team B (3-2)
Team C - Team D (1-0)
Any ideas on how to parse and display this data correctly? I’m new to working with JSON and could use some help. Thanks!
I’ve been in your shoes before, and I know how frustrating it can be to work with JSON data, especially when you’re new to it. From my experience, one effective way to handle this is by using a combination of object destructuring and map() function. Here’s what worked for me:
success: function(data) {
const { games } = data.query;
const formattedGames = games.map(({ homeTeam, awayTeam, score }) =>
`${homeTeam} - ${awayTeam} (${score})`
).join('<br>');
$('#results').html(formattedGames);
}
This approach assumes your data structure has a ‘games’ array inside ‘query’. It extracts the relevant information for each game and formats it as you specified. The join() method at the end converts the array to a string with line breaks.
Remember to always console.log your data first to understand its structure. Also, consider adding error handling to make your code more robust. Good luck with your project!
hey, have u tried using JSON.stringify()? it can help display the whole object. like this:
$('#results').html(JSON.stringify(data, null, 2));
this’ll show everything in a readable format. then u can pick out the parts u need. hope this helps!
I’ve dealt with similar issues before. The problem likely stems from how you’re accessing the data structure. Instead of directly using data.query.scores, try iterating through the data object to extract the information you need. Here’s a basic approach:
success: function(data) {
var output = '';
data.query.results.forEach(function(game) {
output += game.home_team + ' - ' + game.away_team + ' (' + game.score + ')<br>';
});
$('#results').html(output);
}
This assumes the API returns data in a specific format. You might need to adjust the object keys based on the actual structure. Also, consider using template literals for cleaner string concatenation if you’re using modern JavaScript. Remember to handle potential errors and edge cases for a more robust solution.