我没有从数据库获取任何数据到javascript,但我将数据传输到PHP
我使用 AJAX 从数据库中获取数据,并从PHP文件中获取数据到JavaScript,我想使用JavaScript过滤数据,因此我使用JavaScript获取数据以显示产品,我没有将数据获取到JavaScript,而是将数据获取到PHP文件。
$.ajax({
url: 'user.php',
type: 'GET',
datatype: 'json',
success: function (data) {
}
});
function ajax() {
const xhr = new XMLHttpRequest;
xhr.open('GET', 'user.php', true);
xhr.send();
xhr.onload = () => {
if (this.readyState == 4 && this.status == 200) {
let products = JSON.parse(this.responseText);
console.log(products);
}
}
}
const section = document.querySelector('.cards');
const btnContainer = document.querySelector('.top ul');
window.addEventListener('DOMContentLoaded', () => {
displayProductItems(products);
displayMenuButtons();
});
function displayProductItems(productItems) {
let displayProducts = productItems.map((item) => {
return `<div class="card">
<img src="${item.image}" alt="">
<h3>${item.title}</h3>
<div class="bottom">
<span class="text-accent-2">${item.category}</span>
<span class="price">$${item.price}</span>
</div>
</div>`;
});
displayProducts = displayProducts.join("");
section.innerHTML = displayProducts;
}
function displayMenuButtons() {
const sub_categories = products.reduce((values, item) => {
if (!values.includes(item.sub_category)) {
values.push(item.sub_category);
}
return values;
}, ['all']);
const buttons = sub_categories.map((sub_cat) => {
return `<li><button class="filter-btn" data-id="${sub_cat}">${sub_cat}</button></li>`
}).join("");
btnContainer.innerHTML = buttons;
const filterBtn = document.querySelectorAll('.filter-btn');
filterBtn.forEach((btn) => {
btn.addEventListener('click', (e) => {
const sub_cat = e.currentTarget.dataset.id;
const productsSubCat = products.filter((productItem) => {
if (productItem.sub_category === sub_cat) {
return productItem;
};
});
if (sub_cat === 'all') {
displayProductItems(products);
} else {
displayProductItems(productsSubCat);
}
});
});
}
1条答案
按热度按时间fhity93d1#
试试这个代码
我希望它能起作用!