以下是一个基本的Ajax筛选-显示帖子的示例代码:
// 获取帖子数据
function getPosts(category) {
// 发送Ajax请求,获取指定类别的帖子数据
// 这里可以使用fetch或者$.ajax等方法发送请求
// 假设服务器返回的数据为一个包含帖子对象的数组
return fetch('/api/posts?category=' + category)
.then(response => response.json());
}
// 更新帖子列表
function updatePostList(posts) {
var postList = document.getElementById('post-list');
// 清空帖子列表
postList.innerHTML = '';
// 遍历帖子数组,创建帖子元素并添加到列表中
posts.forEach(function(post) {
var postElement = document.createElement('div');
postElement.innerHTML = post.title;
postList.appendChild(postElement);
});
}
// 监听类别选择改变事件
document.getElementById('category-select').addEventListener('change', function() {
var selectedCategory = this.value;
// 如果选择的类别为'all',则获取全部帖子
if (selectedCategory === 'all') {
getPosts()
.then(updatePostList);
} else {
getPosts(selectedCategory)
.then(updatePostList);
}
});
在这个示例中,当用户选择不同的类别时,会发送Ajax请求到服务器,获取对应类别的帖子数据。然后,通过更新帖子列表的函数将帖子数据显示在页面上。