显示来自JSON的图像和标题,但消息显示无法读取未定义的属性“图像”

时间:2019-01-15 15:16:04

标签: jquery json ajax

<section id="panel">
  <div class="container">
  </div> 
</section>
{
  "list": [{
      "image": "cat.jpg",
      "name": "meow"
    }, {
      "image": "dog.jpg",
      "name": "woof"
    }, {
      "image": "sheep.jpg",
      "name": "baaa"
    }, {
      "image": "bird.jpg",
      "name": "chirp"
    }
  ]
} 

$(document).ready(function () {
  $.ajax({
    url: 'https-url',
    type: 'GET',
    dataType: 'json',

    success: function (data) {
      $.each(data.list, function (i, item) {
        $("#panel .container .col-sm-6").remove();

        var lastItems = data.list.slice(-2);
        var content = '<div class="col-sm-6">';

        content += '<img class="img-responsive" src="' + lastItems[i].image + '" alt="' + lastItems[i].name + '"/>';
        content += '<p>' + lastItems[i].name + '</p>';
        content += '</div></div>';

        $("#panel .container").append(content);
      });
    },
    error: function (data) {
      alert('failed');
    }
  });
});

Json会更长一些,但是不管长号如何,我都想获取最后2个细节(图像和名称),例如“绵羊”和“鸟”。 item.imageitem.name似乎可以使用,但有最后两个详细信息,尝试使用lastItem[i].image(名称相同)并收到错误消息。请帮我一些指导。预先谢谢你。

1 个答案:

答案 0 :(得分:1)

您的代码有2个问题

  1. 您正在代码中获取属性covername,而在JSON中则是imagename
  2. 在每个循环中,您的索引都比要查找项目的列表大(lastItems)。在您的示例i变量中,值可以为3, lastItems的最后一个索引为1时(因为大小为2)。因此,您的成功功能应如下所示:

     var lastItems = data.list.slice(-2);
    
    //You remove the item (this is not necesary to put it into the each loop cause it will return one item (due to you are looking for the element that has that id), if you have more than one then you have to loop through and do something like $(this).remove();
    $("#panel .container .col-sm-6").remove();
    
    //You fill the last 2 items
    $.each(lastItems, function(i, item) {
    
    var content = '<div class="col-sm-6">';
    content += '<img class="img-responsive" src="' + lastItems[i].cover + '" alt="' + lastItems[i].name + '"/>';
    content += '<p>' + lastItems[i].name + '</p>';
    content += '</div></div>';
    $("#panel .container").append(content); //This will cause an error casue the element with the id #panel will no longer exist (it will be erased with the last remove() call
    });