【问题标题】:Displaying JSON array through ajax (jquery)通过 ajax (jquery) 显示 JSON 数组
【发布时间】:2010-02-23 14:58:52
【问题描述】:

我对 Ajax 和 JSON 还很陌生,并试图让它工作,但似乎无法掌握它。

如何在ajax中调用json并显示json文件中的所有信息?

这是我的 json 文件

{
  posts: [{
    "image": "images/bbtv.jpg",
    "alter": "BioBusiness.TV",
    "desc": "BioBusiness.TV",
    "website": "http://andybudd.com/"
  }, {
    "image": "images/grow.jpg",
    "alter": "Grow Staffing",
    "desc": "Grow Staffing",
    "website": "http://growstaffing.com/"
  }]
}

和我正在使用的 ajax 函数

$.ajax({
  type: "GET",
  url: "category/all.js",
  dataType: "json",
  cache: false,
  contentType: "application/json",
  success: function(data) {

    $.each(data.posts, function(i, post) {
      $('#folio').html('<ul><li><div class="boxgrid captionfull"><img src="' + post.image + '" alt="' + post.alter + '" /><div class="cover boxcaption"><p>' + post.desc + '</p><a href="' + post.website + '" target="_blank">More Work</a></div></div></li></ul>');

    });
    initBinding();
  },
  error: function(xhr, status, error) {
    alert(xhr.status);
  }
});

由于某种原因,它只显示最后一项......

对正确方向的任何帮助都会很棒。

谢谢!

【问题讨论】:

    标签: jquery ajax json arrays


    【解决方案1】:

    试试这样的:

    $('#folio').html("<ul/>");
    $.each(data.posts, function(i,post){
       $('#folio ul').append('<li><div class="boxgrid captionfull"><img src="' + post.image + '" alt="' + post.alter + '" /><div class="cover boxcaption"><p>' + post.desc + '</p><a href="' + post.website + '" target="_blank">More Work</a></div></div></li>');
    });
    

    【讨论】:

    • 非常感谢!效果很好。不敢相信我花了几个小时试图解决这个问题。 :)
    【解决方案2】:

    您正在覆盖每个循环中#folio 中的 html,您需要连接到它

    尝试先添加 UL,然后为每个循环 .append() 附加一个 LI 到 UL

    【讨论】:

    • 感谢您引导我走向正确的方向。它帮助我准确理解我做错了什么。
    猜你喜欢
    • 2013-01-09
    • 2015-12-08
    • 1970-01-01
    • 2015-07-20
    • 2020-03-09
    • 1970-01-01
    • 2018-06-12
    • 2018-01-23
    • 2011-02-10
    相关资源
    最近更新 更多