我可以在JavaScript上使用img标签来显示存储在MongoDB中的图像吗?

时间:2018-04-04 14:51:19

标签: javascript html mongodb

我在HTML表格上显示我的图片时遇到了麻烦。图像存储在MongoDB中。我可以使用JavaScript上的<img>标记来显示我的图片吗?还是有另一种方法可以做到这一点吗?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>E-commerce Website</title>
        <script>  
            function loadBasket(){
                var basketArray;
                var tableBody;
                var tableHeader = "<tr><th>Product Image</th><th>Product Name</th><th>Price</th></tr>\n";
                for(var i=0; i<basketArray.length; ++i){
                    tableBody += "<tr><td>" + "<img class='categories_img' src='"basketArray[i].image"'>" + "</td><td>" + basketArray[i].name + "</td><td>" + basketArray[i].price + "</td></tr>";
                }
            }
        </script>
    </head> 
    <body onload="loadBasket()"> 
        <table id="basket_list"></table>
    </body>
</html>

2 个答案:

答案 0 :(得分:2)

您的图像文件名部分缺少连接运算符。您需要将该行更改为以下内容:

tableBody += "<tr><td>" + "<img class='categories_img' src='"+basketArray[i].image+"'>" + "</td><td>" + basketArray[i].name + "</td><td>" + basketArray[i].price + "</td></tr>";

答案 1 :(得分:1)

你遗漏了一些东西:

  1. 您不会将html插入表<table id="basket_list"></table>
  2. basketArray是空的。
  3. <html xmlns="http://www.w3.org/1999/xhtml">
    
    <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
      <title>E-commerce Website</title>
      <script>
        function loadBasket() {
          var basketArray = [{
            image: "https://i.stack.imgur.com/eTem9.jpg?s=48&g=1",
            name: "test",
            price: "10"
          }];
          var tableBody = "";
          var tableHeader = "<tr><th>Product Image</th><th>Product Name</th><th>Price</th></tr>\n";
          for (var i = 0; i < basketArray.length; ++i) {
            tableBody += "<tr><td>" + "<img class='categories_img' src='" + basketArray[i].image + "'>" + "</td><td>" + basketArray[i].name + "</td><td>" + basketArray[i].price + "</td></tr>";
          }
          document.getElementById('basket_list').innerHTML = tableHeader + tableBody;
        }
      </script>
    </head>
    
    <body onload="loadBasket()">
      <table id="basket_list"></table>
    
    </body>
    
    </html>

    codepen