简体   繁体   中英

How can I assign dictionary values to javascript variables (jQuery / AJAX API call returned in JSON)

I have a well running AJAX request that queries data from a third party API that returns the data in JSON. I now want to assign the values from the returned JSON data to javascript variables to make further manipulation to the data itself in my AJAX success function before updating the frontend.

In the below example I would like to assign the value of key name to my Javascript team variable.

What would be the best way to accomplish this?

This is the returned structure:

{ 
   "api":{ 
      "results":1,
      "teams":[ 
         { 
            "team_id":66,
            "name":"Barcelona",
            "code":null,
            "logo":"Not available in Demo",
            "country":"Spain",
            "founded":1899,
            "venue_name":"Camp Nou",
            "venue_surface":"grass",
            "venue_address":"Carrer d'Ar\u00edstides Maillol",
            "venue_city":"Barcelona",
            "venue_capacity":99787
         }
      ],

This is my AJAX request:

$('ul.subbar li a').on('click', function(e) {
e.preventDefault();
var team_id = $(this).attr("id");
console.log(team_id);
$.ajax({
  method: "GET",
  dataType: "json",
  url: "https://cors-anywhere.herokuapp.com/http://www.api-football.com/demo/api/v2/teams/team/" + team_id,
  success: function(response) {
    var team_data = response
    console.log(team_data)

    team = // how to assign team name from API callback to variable

    console.log(team)

    $("#selectedClub").html(response);

    }
  });
});

You can use dot notation to navigate through objects

team_data.api.teams[0].name //output: "barcelona"

In you example there is only one item inside teams array , so the above example should works fine, but let's suppose that in your response there is more than 1 team on teams then you could do something like this:

var teamList = [];
$.each(team_data.api.teams, function(index, team){
    teamList.push(team.name);
})

and it will give an array with all team names from your ajax response

put JSON in js obj variable


var obj = JSON.parse('{ <key:value>,<key:value>...}');

Make sure the text is written in JSON format, or else you will get a syntax error.


Use the JavaScript object in your page: Example


<p id="demo"></p>

<script>
document.getElementById("name").innerHTML = obj.name + ", " + obj.country;
</script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM