首页 > 解决方案 > 显示来自 json 的图像和标题,但消息说无法读取未定义的属性“图像”

问题描述

<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 会更长,但不管数字多长,我想获取最后两个细节(图像和名称),例如“羊”和“鸟”。item.image并且item.name似乎可以工作,但最后 2 个详细信息,尝试使用lastItem[i].image(名称相同)并收到错误消息。请帮我一些指导。先感谢您。

标签: jqueryjsonajax

解决方案


你的代码有2个问题

  1. 您正在代码中获取属性covername而在您的 JSON 中是imagename
  2. 在每个循环中,您将有一个大于您要查找的项目的列表大小的索引 ( lastItems) 在您的示例变量中,当最后一个索引为 1 时(因为大小为 2) ,您的示例i变量可以获得值 3 。lastItems所以你的成功函数应该是这样的:

     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
    });
    

推荐阅读