0

I have one api link that contains the top elements. From each element, I need to build the end of a second api call which will give me the rest of the elements I need and pull them out.

Let say the first json is (urlphonebrands) that contains 3 phone brands (Apple, Samsung & Nokia). The second json call depends on each brand name, like urlphonebrands/Nokia, or urlphonebrands/Samsung or urlphonebrands/Apple built automatically.

I need to loop through each brand name to get properties such as colors, battery life and size. But each color has another loop of choices, as for example, black, white, red. My end result will be,

Apple
    battery life: 
        6h
    color: 
        blue 
        black
Samsung: 
    battery life: 
        6h
    color:
        blue 
        black
Nokia:
    battery life: 
        3h
    color: 
        blue 

While I am able to loop through each top element successfully I can only retrieve the last color element of the first item, which indicates that I built the second loop incorrectly. Went a few hours through it and figured I could use some help. This is what I have,

$.getJSON("urlphonebrands", function(data){

    var brandBlock = data[0]['name'];

    $.each(data, function(index, brandBlock){

        var brand = brandBlock.name;

        $('#table').append('<tr><td>' + brand + '</td></tr>');

        //It works fine until this point

        $.getJSON("phonebrandsurl" + brand, function(data){

            $.each(brand, function (index2, brand){

                var color = data[0].name[0].color;

                $('#table').append('<tr><td>' + color + '</td></tr>');

            });


        });


    });

});

Which gives me something like,

Apple
    blue
    blue
Samsung
    blue
    blue
Nokia
    blue

This is the console.log output after the second api call,

[Object]
0: Object
brand: Array[17]
0: Object
battery life: "6h"
colors: Object
color: "blue"
4

1 回答 1

2

尝试将第二个包装getJSON到匿名函数中并将品牌作为参数传递::

(function(brand){
  $.getJSON('phonebrandsurl' + brand, function(data){
  // ...
}(brand))
于 2013-01-06T10:21:31.810 回答