简体   繁体   English

从JSON文件中检索图像,该文件位于数据库中并以HTML img标记显示

[英]Retrieve image from JSON file which is in the database and display in HTML img tag

I really dont know where the hell i am wrong. 我真的不知道我到底哪里错了。 May be it is simple but I can't figure it out. 可能很简单,但我无法弄清楚。 Any help would be great, please and thank you. 任何帮助都会很棒,拜托并谢谢。

JSON code (it is stored in 'images' column in tblproducts table in the database) JSON代码(它存储在数据库中tblproducts表的'images'列中)

{"200x200":"http://img.fkcdn.com/image/mobile/p/s/u/lenovo-k6-power-k33a42-200x200-imaezt6hypjzhdug.jpeg","400x400":"http://img.fkcdn.com/image/mobile/p/s/u/lenovo-k6-power-k33a42-400x400-imaezt6hypjzhdug.jpeg","800x800":"http://img.fkcdn.com/image/mobile/p/s/u/lenovo-k6-power-k33a42-800x800-imaezt6hypjzhdug.jpeg","unknown":"http://img.fkcdn.com/image/mobile/p/s/u/lenovo-k6-power-k33a42-original-imaezt6hypjzhdug.jpeg"}

HTML & PHP Code: HTML和PHP代码:

<?php 
   $category_id = $_GET['category_id'];
   $result = mysql_query("select * from tblproducts where category_id = '$category_id");
   while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
?>
<script>
  var data = 
      data.forEach( function(obj) {
          var img = new Image();
          img.src = obj.Img1;
          img.setAttribute("class", "banner-img");
          img.setAttribute("alt", "effy");
          document.getElementById("img-container").appendChild(img);
      });
</script>
    <img id="img-container" alt=" " class="img-responsive" /> 
    <h5>
        <a target="_blank" href="<?php echo $row['product_url']; ?>">
           <?php echo $row['product_title']; ?>
        </a>
    </h5>
   <?php echo $row['maximum_price']; ?>
<?php } ?>

I have no idea about the javascript and how to fetch each of the image from the json and display it in different tag. 我不知道javascript以及如何从json中获取每个图像并将其显示在不同的标记中。 Please help... Thanks in advance 请帮忙......先谢谢

Assuming your JSON is stored as string in column images . 假设您的JSON在列images存储为字符串。 You can do something like this: 你可以这样做:

// ...
<script>
  var data = <?php echo json_decode($row['images']); ?>
      Object.keys(data).forEach(function(key) {
          var img = new Image();
          img.src = data[key];
          img.setAttribute("class", "banner-img");
          img.setAttribute("alt", "effy");
          img.classList.add('img-responsive');
          document.getElementById("img-container").appendChild(img);
      });
</script>
    <div id="img-container"></div>
    <h5>
        <a target="_blank" href="<?php echo $row['product_url']; ?>">
           <?php echo $row['product_title']; ?>
        </a>
    </h5>
// ...

I've changed the image append logic, what you were doing was wrong. 我改变了图像附加逻辑,你所做的是错误的。 You cannot append images that way, instead create a container and append the newly created images in that container. 您不能以这种方式附加图像,而是创建一个容器并将新创建的图像附加到该容器中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM