【问题标题】:json image file not displaying in htmljson图像文件未在html中显示
【发布时间】:2021-05-11 02:26:22
【问题描述】:

我的服务器中有一个 json 文件,我正在尝试在我的 html 网站中显示它,我执行了以下代码:

var data = {
  "images": [{
    "bannerImg1": "http://molugu.com/yantraev/animation.json"
  },
  ]
};
data.images.forEach( function(obj) {
  var img = new Image();
  img.src = obj.bannerImg1;
  img.setAttribute("class", "banner-img");
  img.setAttribute("alt", "effy");
  document.getElementById("img-container").appendChild(img);
});
<div class="banner-section" id="img-container">
    </div>

但是这里没有显示json,谁能告诉我这里出了什么问题,提前谢谢

【问题讨论】:

    标签: javascript html json image


    【解决方案1】:

    @Zubair Nazar 你用来解释这些的示例文件将不起作用。看起来示例 json 文件是从 lottie 导出的动画 json 文件。

    查看这个小提琴以获取实时实现https://jsfiddle.net/87Lf6by0/

    const logoSvgData = 'http://molugu.com/yantraev/animation.json';
    const animation = bodymovin.loadAnimation({
      container: document.getElementById('logo-bm'),
      renderer: 'svg',
      loop: true,
      autoplay: true,
      animationData: logoSvgData
    })
    #logo-bm {
      width: 400px;
      height: auto;
    }
    <div id="logo-bm"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.5.3/lottie.js"></script>

    【讨论】:

    • 兄弟我只想显示那个json文件,那个json里面的动画
    • 让我试试,等一下
    • 查看此jsfiddle.net/87Lf6by0 以查看实现
    【解决方案2】:

    &lt;img&gt; 元素用于显示图像。

    JSON 是一种基于文本的序列化数据格式。这不是图像。

    一般来说,要显示 JSON,您会使用 Ajax API(例如 fetch)请求它,然后生成一些针对特定数据格式定制的 HTML 元素,这些数据格式编码在该 JSON 中,然后您将使用 DOM 方法插入这些元素。

    【讨论】:

    • 我是新手,你能不能把它作为一个例子或给我参考链接
    【解决方案3】:

    请像这样尝试。

    var data = {
      "images": [{
        "bannerImg1": "http://molugu.com/yantraev/animation.json"
      },
      ]
    };
    data.images.forEach( function(obj) {
    
       fetch(obj.bannerImg1, 
            {
                method: "GET", 
                mode: 'cors',
                headers: {
                    'Content-Type': 'application/json',
                }
            }
        ).then(response => response.json())
        .then(data => {
           data.assets.forEach(function(image){
              img.src = image.p;
              img.setAttribute("class", "banner-img");
              img.setAttribute("alt", "effy");
              document.getElementById("img-container").appendChild(img);
           });
    
        })
        .catch((err) => {
            console.log(err);
        })
     
    
    });
    <div class="banner-section" id="img-container">
     </div>
    

    【讨论】:

      猜你喜欢
      • 2017-12-16
      • 1970-01-01
      • 2023-01-28
      • 2020-06-19
      • 2020-11-25
      • 1970-01-01
      • 2014-02-21
      • 2011-08-06
      • 1970-01-01
      相关资源
      最近更新 更多