0
{
    "prev": [
        "demo/medium/Web081112_P002_medium.jpg",
        "demo/medium/Web081112_P003_medium.jpg"
    ],
    "curr": [
        "demo/medium/Web081112_P004_medium.jpg",
        "demo/medium/Web081112_P005_medium.jpg"
    ],
    "next": [
        "demo/medium/Web081112_P006_medium.jpg",
        "demo/medium/Web081112_P007_medium.jpg"
    ]
}

This is the json I got :

<script>
  $(document).ready(function(){
       $.ajax({
        type: "GET",
        url: "scandir.php",
        data: "page=5",
        dataType: 'json',
        success: function (data) { 
        $.each(data, function(i, data){
        $('#img'+i).attr('src',data[1]);
    });
    }
});
});
</script> 

I would like to do this: Assign <img id = "img1" src="demo/medium/Web081112_P002_medium.jpg"> and so on....

The collected data [1] only capture the values in column (3,5,7) . How to implement this? Thanks

user782104
  • 13,233
  • 55
  • 172
  • 312
  • To be precise, how to use each to iteractive – user782104 Dec 05 '12 at 10:41
  • Refer [this][1] answer. Follow this. [1]: http://stackoverflow.com/questions/13720815/capture-a-div-as-an-image/13720980#13720980 – Earth Dec 05 '12 at 10:42
  • Could you please describe how to get the id `img1` from the keys `prev` and `0`? Notice that properties in an object are not ordered. – Bergi Dec 05 '12 at 10:50

3 Answers3

0

Try this if your array always has two elements:

$.each(data, function(i, data){
    $('#img'+(2*i)).attr('src',data[0]);
    $('#img'+(2*i + 1)).attr('src',data[1]);
});

If you have more than two, then you'll need an inner loop:

var idx = 0;
$.each(data, function(i, data) {
    $.each(data[i], function(j, dataj) {
        $('#img'+(idx)).attr('src',dataj[j]);
        ++idx;
    });
});
Stefan
  • 4,166
  • 3
  • 33
  • 47
0

That's not a multidimensional array, that is an object that has arrays as properties.

To loop through the arrays, you need another loop inside the loop. Use a separate counter to keep track of the image numbering.

var count = 1;
$.each(data, function(i, row){
  $.each(row, function(j, item){
    $('#img' + count).attr('src', item);
    count++;
  });
});

Note: There is no specific order to the properties in an object, so they may end up in different order depending on which browser the visitor is using.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

since your are just setting the src attribute of the second data object here...

$('#img'+i).attr('src',data[1]);

you are getting the (3,7,5) only...

you have to use two $.each loops to get all the src..

try this

var k=1;

$.each(data, function(i, data1){
  $.each(data1, function(j, data2){
     $('#img' + k).attr('src', data2);
       k++;
   });
});
bipen
  • 36,319
  • 9
  • 49
  • 62