vendredi 31 juillet 2015

Get AJAX Request and Looping Through JSON

I am using a GET ajax request to retrieve some JSON data from the database. I want to loop through it and print certain items. For example, I want to print all the address in stylist_1 only. The problem is that it only prints the last item.

Here's what the code looks like:

var stylist1Addresses;

    function getData() {
        $.ajax({
            url: '/getData',
            type: 'GET',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            async: false,
            success: function (data) {
                for (var i = 0; i < data.stylist_1.length; i++) {
                    stylist1Addresses = data.stylist_1[i];
                }
            }
        });
        console.log(stylist1Addresses);
    }

Sample data:

{
  "stylist_1": [
    {
      "Address": "1 Stn Main", 
      "Phone": "403-990-9033"
    }, 
    {
      "Address": "474 Cirrus Rd", 
      "Phone": "403-995-3243"
    }, 
    {
      "Address": "1591 Stn St", 
      "Phone": "403-982-8893"
    }
  ], 
  "stylist_2": [
    {
      "Address": "219 Welch Blvd", 
      "Phone": "587-436-3171"
    }, 
    {
      "Address": "374 Main Rd", 
      "Phone": "587-315-9431"
    }, 
    {
      "Address": "564 Main Rd", 
      "Phone": "403-938-9983"
    }
  ]
}

Aucun commentaire:

Enregistrer un commentaire