insertAdjacentHTML()不使用onload函数将项目组合项插入到项目组合列表中

时间:2018-02-09 05:07:56

标签: javascript jquery html mysql dom

使用mySQL数据库中的'food'表,我计划从中获取值并将其显示在投资组合中。但是,当我尝试这样做时,只有我的投资组合过滤器出现在我的网站上。我已经将displayFoods()函数存储在一个单独的.js文件中,并在我的index.html文件中引用它。

使用console.log,我确定在我的body标签中使用onload确实调用了displayFoods(),并正确加载了我的值。我不确定我要插入的HTML代码。感谢您解决此问题的任何帮助,谢谢!

onload功能:

function displayFoods() {
    var request = new XMLHttpRequest();

    request.open("GET", food_url, true);
    request.setRequestHeader("Content-Type", "application/json");
    request.onload = function() {
    // We create a 'foods' variable to store data of all foods retrieved  
    // from the server.
    // All foods will be stored in the form of an array in the foods variable.
        var foods = JSON.parse(request.responseText);

        var totalFoods = foods.length;
        console.log(totalFoods);
        // Get the HTML element of the div where id="foodlist" so that
        // we can add HTML codes to display all the foods.
        var listings = document.getElementById("foodlist");

        // We use a for loop to traverse through the array of foods.
        // For every food, we get the name, info, foodType, price, pictureSmall and pictureLarge. 
        for (var count = 0; count < totalFoods; count++) {
            var name = foods[count].name;
            var info = foods[count].info;
            var foodType = foods[count].foodType;
            var price = foods[count].price;
            var pictureSmall = foods[count].pictureSmall;
            var pictureLarge = foods[count].pictureLarge;

            console.log(count);
            console.log(name);
            console.log(info);
            console.log(foodType);
            console.log(price);
            console.log(pictureSmall);
            console.log(pictureLarge);

            // We create the HTML codes for displaying each food and store in a variable 'foodItem'.
            // We also insert each food value (name, info, etc.) in the HTML codes. 
            var foodItem = 
                  '<div class="portfolio-item '+foodType+' col-xs-12 col-sm-4 col-md-3"> \
                    <div class="recent-work-wrap"> \
                      <img class="img-responsive" src="'+pictureSmall+'" alt=""> \
                      <div class="overlay"> \
                        <div class="recent-work-inner"> \
                          <h3> \
                            <a href="#">'+name+'</a> \
                          </h3> \
                           <p>'+info+' \
                            <br>$'+price+'0</p> \
                          <a class="preview" href="'+pictureLarge+'" rel="prettyPhoto"> \
                            <i class="fa fa-eye"></i> View</a> \
                        </div> \
                      </div> \
                    </div> \
                  </div>';

            console.log(foodItem);

            // We use the built-in JavaScript function insertAdjacentHTML() which is from 
            // the HTML element object to insert the HTML codes.                  
            listings.insertAdjacentHTML('beforeend', foodItem);
        }
    };

    // Send the request to get info of all foods.
    request.send();
}

尝试使用displayFoods()的投资组合代码:

<section id="portfolio">
  <div class="container">
    <div class="center">
      <div class="col-md-6 col-md-offset-3">
        <h2>Menu</h2>
        <hr>
        <p class="lead">Take a look at our selects!</p>
      </div>
    </div>
  </div>

  <div class="container">
    <div class="col-lg-12">
      <ul class="portfolio-filter text-center">
        <li>
          <a class="btn btn-default active" href="#" data-filter="*">All Items</a>
        </li>
        <li>
          <a class="btn btn-default" href="#" data-filter=".alacarte">A la carte</a>
        </li>
        <li>
          <a class="btn btn-default" href="#" data-filter=".drinks">Drinks</a>
        </li>
        <li>
          <a class="btn btn-default" href="#" data-filter=".desserts">Desserts</a>
        </li>
      </ul>
      <!--/#portfolio-filter-->

      <div class="row">
        <div class="portfolio-items">
          <div id="foodlist"></div>
        </div>
      </div>
    </div>
  </div>
</section>

硬编码的投资组合代码:

<section id="portfolio">
  <div class="container">
    <div class="center">
      <div class="col-md-6 col-md-offset-3">
        <h2>Menu</h2>
        <hr>
        <p class="lead">Take a look at our selects!</p>
      </div>
    </div>
  </div>

  <div class="container">
    <div class="col-lg-12">
      <ul class="portfolio-filter text-center">
        <li>
          <a class="btn btn-default active" href="#" data-filter="*">All Items</a>
        </li>
        <li>
          <a class="btn btn-default" href="#" data-filter=".alacarte">Sandwiches</a>
        </li>
        <li>
          <a class="btn btn-default" href="#" data-filter=".drinks">Drinks</a>
        </li>
        <li>
          <a class="btn btn-default" href="#" data-filter=".desserts">Desserts</a>
        </li>
      </ul>
      <!--/#portfolio-filter-->

      <div class="row">
        <div class="portfolio-items">


          <!--/.portfolio-item-->

          <div class="portfolio-item alacarte col-xs-12 col-sm-4 col-md-3">
            <div class="recent-work-wrap">
              <img class="img-responsive" src="images/portfolio/recent-new/hamncheese.png" alt="">
              <div class="overlay">
                <div class="recent-work-inner">
                  <h3>
                    <a href="#">Ham and Cheese Sandwich</a>
                  </h3>
                  <p>Ham, Cheese, Brioche Bread
                    <br>$1</p>
                  <a class="preview" href="images/portfolio/full-new/hamncheese.png" rel="prettyPhoto">
                    <i class="fa fa-eye"></i> View</a>
                </div>
              </div>
            </div>
          </div>

          <!--/.portfolio-item-->

        </div>
      </div>
    </div>
  </div>
</section>
<!--/#portfolio-item-->

.portfolio-item在这里重复了两次,食物表中有不同的值,所以我会把它剪掉。

listFoods.html代码: 这是一个包含js脚本的.html文件,全部在一个文件中。它工作正常,但它没有使用投资组合。

<!doctype html>
<html>

<head>
    <title>List Foods</title>
    <style>
        .grid-container {
            display: grid;
            grid-template-columns: auto auto auto;
            background-color: #2196F3;
            padding: 10px;
        }

        .grid-item {
            background-color: rgba(255, 255, 255, 0.8);
            border: 1px solid rgba(0, 0, 0, 0.8);
            padding: 20px;
            font-size: 30px;
            text-align: center;
        }
    </style>
    <script>
        function displayFoods() {
            var request = new XMLHttpRequest();

            // The route pattern '/movies' is registered in the routeMovies.js file.
            request.open("GET", "/food", true);
            request.setRequestHeader("Content-Type", "application/json");
            request.onload = function() {
                // We create a 'movies' variable to store data of all movies retrieved  
                // from the server.
                // All movies will be stored in the form of an array in the movies variable.
                var foods = JSON.parse(request.responseText);

                var totalFoods = foods.length;
                // Get the HTML element of the div where id="movieListings" so that
                // we can add HTML codes to display all the movies.
                var listings = document.getElementById("foodListings");

                // We use a for loop to traverse through the array of movies.
                // For every movie, we get the name and picture. 
                for (var count = 0; count < totalFoods; count++) {
                    var name = foods[count].name;
                    var pictureSmall = foods[count].pictureSmall;
                    var pictureLarge = foods[count].pictureLarge;
                    var foodType = foods[count].foodType;
                    var info = foods[count].info;
                    var price = foods[count].price;

                    // We create the HTML codes for displaying each movie and store in a variable 'movieItem'.
                    // We also insert each movie name and picture in the HTML codes. 
                    var foodItem = '<div class="grid-item">                \
                        <img src="' + pictureSmall + '">       \
                        <h3>' + name + '</h3>              \
                     </div>';

                    // We use the built-in JavaScript function insertAdjacentHTML() which is from 
                    // the HTML element object to insert the HTML codes.                  
                    listings.insertAdjacentHTML('beforeend', foodItem);
                }
            };

            // Send the request to get info of all movies.
            request.send();
        }
    </script>
</head>

<!-- When this page loads, execute the JavaScript displayMovies() function that we created above. -->

<body onload="displayFoods()">
    <!-- We create a div element that will display the list of movies. -->
    <!-- We use a CSS class 'grid-container' that we create in this page to organise the display. -->
    <div id="foodListings" class="grid-container"></div>
</body>

</html>

console.log(foodItem); result

再次感谢!

0 个答案:

没有答案