<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文章列表页</title>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>
<button class="filter-btn" data-category="all">全部文章</button>
<button class="filter-btn" data-category="technology">科技</button>
<button class="filter-btn" data-category="travel">旅行</button>
<button class="filter-btn" data-category="health">健康</button>
<div id="article-list">
<!-- 文章列表将通过Ajax加载到这里 -->
</div>
<script src="script.js"></script>
</body>
</html>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$category = $_POST['category'];
// 查询数据库或生成文章数据
$articles = array(
array('title' => '文章1', 'category' => 'technology', 'content' => '内容1'),
array('title' => '文章2', 'category' => 'travel', 'content' => '内容2'),
array('title' => '文章3', 'category' => 'health', 'content' => '内容3'),
// 添加更多文章数据
);
// 根据类别过滤文章
if ($category !== 'all') {
$articles = array_filter($articles, function ($article) use ($category) {
return $article['category'] === $category;
});
}
header('Content-Type: application/json');
echo json_encode($articles);
} else {
// 如果不是POST请求,返回错误信息
header('HTTP/1.1 405 Method Not Allowed');
echo 'Invalid request method.';
}
?>
$(document).ready(function () {
// 默认加载全部文章
loadArticles('all');
// 点击按钮时,根据按钮的data-category属性加载相应类别的文章
$('.filter-btn').click(function () {
var category = $(this).data('category');
loadArticles(category);
});
function loadArticles(category) {
$.ajax({
url: 'data.php',
type: 'POST', // 使用POST方式
dataType: 'json',
data: {category: category}, // 发送数据到服务器
success: function (data) {
displayArticles(data, category);
},
error: function () {
console.log('Error loading articles.');
}
});
}
function displayArticles(articles, category) {
console.log(articles);
var filteredArticles = (category === 'all') ? articles : articles.filter(article => article.category === category);
var articleList = $('#article-list');
articleList.empty();//
$.each(filteredArticles, function (index, article) {
var articleHTML = '<div class="article">';
articleHTML += '<h2>' + article.title + '</h2>';
articleHTML += '<p>' + article.content + '</p>';
articleHTML += '<p><strong>Category:</strong> ' + article.category + '</p>';
articleHTML += '</div>';
articleList.append(articleHTML);
});
}
});
前两个按钮正常,第三个和第四个 就出错了
Uncaught TypeError: articles.filter is not a function
不会JS,求助大佬们 怎么改
你这个到底是从数据库取值(文章列表)还是就在php文件的静态值(文章列表)?
单看你这儿写的,问题不大,最起码取值,请求没啥问题,问题在展现
直接把:
替换为:
因为后台(php)已经判断过一次了,前端没必要再做一次判断
不如直接问chatgpt
@lexgni #1
使用 4.0 会更准确,有问题,直接复制错误信息 继续问
typeScript中filter的使用方法
@caicaiwoshishui #5

原来这么简单,chatgpt欺负我不懂JS,还写个三元表达式把我绕晕了