简体   繁体   English

使用Ajax获取数据并使用纯JavaScript插入HTML

[英]Fetching data using ajax and inserting in html using plain javascript

I have fetched data from my php/products.php file using ajax and have a html file that I have already styled. 我已经使用Ajax从我的php/products.php文件中获取了数据,并且有一个已经设置样式的html文件。 How can I insert the data I have fetched from the products.php file in the html page? 如何在html页面中插入从products.php文件获取的数据?

Most of my search results are based on jQuery. 我的大部分搜索结果都基于jQuery。

The containers I've used are the containers styled in the css file. 我使用的容器是css文件中样式设置的容器。

The HTML HTML

<div class="container">
      <header class="header">
         <center>
            <h1>Products</h1>
         </center>
      </header>
      <hr>
      <div id="products" class="products"></div>

      <button id="loadButton" class="btn">Load more</button>
   </div>

The JS JS

var loadBtn = document.getElementById('loadButton');

loadBtn.addEventListener('click', fetchProducts);

function fetchProducts() {

   var xhr = new XMLHttpRequest;

   xhr.open('GET', `php/products.php?${q}`, true);

   xhr.onload = function () {
      if (this.status == 200) {
         var products = JSON.parse(this.responseText);

         var output, i;

         for (i = 0; i < products.length; i++) {
            output += `
                     <div id="pCard" class="p-card">
                           <p id="pName" class="p-name">${products[i].name}</p>
                           <p id="pAbout" class="p-about">${products[i].description}</p>
                     </div>
                     `;
         }

         console.log(products);

         document.getElementById('products').innerHTML = output;
      }
   }

   xhr.send();
}

The PHP 的PHP

include 'config.inc.php';

$sqlFetch = "SELECT id,item_name,item_description FROM items ORDER BY id ASC LIMIT 3";

$result = mysqli_query($connection, $sqlFetch);

$products = mysqli_fetch_all($result, MYSQLI_ASSOC);

echo json_encode($products);

I expect the code to parse the containers containing the product name and description to the products container in the HTML page. 我希望代码将包含产品名称和描述的容器解析为HTML页面中的产品容器。 On clicking the loadBtn I want three more products to be loaded on the webpage Instead am getting an error from the console. 在单击loadBtn我希望在网页上再加载三个产品,相反从控制台收到错误消息。

The issue was at the php/products.php?${q} on the JS file. 问题出在JS文件上的php/products.php?${q}

I was also targeting name and description instead of item_name and item_description . 我也定位namedescription而不是item_nameitem_description

`
<div id="pCard" class="p-card">
  <p id="pName" class="p-name">${products[i].name}</p>
  <p id="pAbout" class="p-about">${products[i].description}</p>
</div>
`;

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

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