开发者

jquery looping getJson

Jquery Code

<script type="text/javascript">
$(document)开发者_Python百科.ready(function()
{
$.getJSON("http://localhost/index.php/upload/history",function(data)
{
$.each(data.images, function(i,data)
{
$('#recent').html( '<img src="/t/'  +data.imagename + '">' );
});
}
);
return false;
});
</script>

sample json data

{
    "images": [
        {
            "imagename": "p5Tsa.jpg"
        },
        {
            "imagename": "Z8hjA.jpg"
        },
        {
            "imagename": "0Fnm0.jpg"
        },
        {
            "imagename": "D5Tfa.jpg"
        },
        {
            "imagename": "VDnvu.jpg"
        },
        {
            "imagename": "9spgp.jpg"
        },
        {
            "imagename": "Hg7va.jpg"
        }
    ]
}

This shows only the first image .. but when I use append() , then it shows all the images thats in the json response.. the reason I want to avoid append is that I want to refresh the div usng setInterval().

How to show all the images that I get in the json response using .html() ?

thanks :)


Use append, but clear the html on each fetch.

<script type="text/javascript">
$(document).ready(function()
{
$.getJSON("http://localhost/index.php/upload/history",function(data)
{
$('#recent').html("");
$.each(data.images, function(i,data)
{
$('#recent').append( '<img src="/t/'  +data.imagename + '">' );
});
}
);
return false;
});
</script>


When you call html() you are setting the whole content of the element. There are several ways to solve this. I would do

$.getJSON("http://localhost/index.php/upload/history",function(data) {
    var images = $.map(data.images, function(data) {
        return '<img src="/t/'  +data.imagename + '">';
    }).get();
    $('#recent').html(images.join(''));
});

to only insert into the document once.

You could easily do the same with append, you just have to clear the content before.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜