say this api.football-data.org/v1/competitions
contains the following
{
"_links": {
"teams": {
"href": "http://api.football-data.org/v1/competitions/444/teams"
}
},
"id": 444,
"caption": "Campeonato Brasileiro da Série A",
"league": "BSA"
},
{
"_links": {
"teams": {
"href": "http://api.football-data.org/v1/competitions/445/teams"
}
},
"id": 445,
"caption": "Premier League 2017/18",
"league": "PL"
}
what is the best way to access the specific team? I do it this way, it works but I think it's not very neat.
HTML
Choose Team: <select id="team">
<option value="444">Premier League</option>
<option value="445">Campeonato Brasileiro</option>
</select>
JavaScript
$("#team").change(function(){
var id = $("#team").val();
getTeam(id);
});
function getTeam(id){
$.ajax({
url: 'http://api.football-data.org/v1/competitions/'+id+'/team',
type: 'GET',
dataType: 'json',
success: function(data) {
var team= '';
$.each(data, function(k, v) {
team+= '<tr><td>' + v.name+ '</td></tr>';
});
$("#team").html(team);
}
});
}
Your solution is correct, but you can use the URL returned from API. I think this API was created according to Richardson Maturity Model (more information here: https://martinfowler.com/articles/richardsonMaturityModel.html). The api-football is on level 3 - with hypermedia controls - because the API tell us what we can do next (get teams, get players...)
So, it's can brings some advantages for your application: if the api-football changes some URL, your application won't break.
You can change your solution, if you want:
var apiKey = '7b35712f29da4dc58a538320e57c12cc';
$(function () {
getCompetitions();
$('#competitions').change(function () {
var urlTeam = $("#competitions").find("option:selected").attr('data-href');
getTeam(urlTeam);
});
})
function getCompetitions() {
$.ajax({
url: 'http://api.football-data.org/v1/competitions/',
headers: {
"X-Auth-Token":apiKey
},
type: 'GET',
dataType: 'json',
success: function (data) {
$.each(data, function (k, v) {
$('#competitions').append('<option value="' + v.id + '" data-href="' + v._links.teams.href + '">' + v.caption + '</option>');
});
}
});
}
function getTeam(url)
{
$.ajax({
url: url,
headers: {
"X-Auth-Token":apiKey
},
type: 'GET',
dataType: 'json',
success: function (data) {
var team = '';
$.each(data.teams, function (k, v) {
team += '<tr><td>' + v.name + '</td></tr>';
});
$("#teams").html(team);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label> Choose Competition: </label>
<select id="competitions">
<option>Select...</option>
</select> <br />
<label>Teams </label>
<table id="teams">
</table>
</div>