【问题标题】:jquery looping getJsonjquery循环getJson
【发布时间】:2011-07-24 23:02:53
【问题描述】:

Jquery 代码

<script type="text/javascript">
$(document).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>

示例 json 数据

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

这仅显示第一张图像.. 但是当我使用 append() 时,它会显示 json 响应中的所有图像.. 我想避免附加的原因是我想刷新 div 使用 setInterval( )。

如何使用 .html() 显示我在 json 响应中获得的所有图像?

谢谢:)

【问题讨论】:

    标签: jquery json loops


    【解决方案1】:

    使用追加,但在每次提取时清除 html。

    <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>
    

    【讨论】:

      【解决方案2】:

      当您调用html() 时,您正在设置元素的全部内容。有几种方法可以解决这个问题。我会做的

      $.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(''));
      });
      

      只插入文档一次

      你可以很容易地用append做同样的事情,你只需要先清除内容。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多