如何在HTML页面中过滤从URL接口获取的待办事项数据
问题根因
- 未绑定表单提交事件,点击GO按钮会触发默认表单提交刷新页面,不会执行过滤逻辑
- 接口请求未拼接过滤参数,json-server原生支持
title_like模糊匹配、action精确匹配的查询参数,直接拼在URL后缀即可生效 - 仅在页面初始化时请求了一次全量数据,过滤操作没有触发数据重新拉取/筛选
代码修改
HTML调整(可选,优化体验)
给下拉选择框加一个「全部」的默认选项,避免默认强制筛选WORK类型:
<select name="action"> <option value="">全部</option> <option value="WORK">Work</option> <option value="SPORT">Sport</option> <option value="SHOPING">Shopping</option> <option value="MUSIC">Music</option> </select>
JavaScript完整修改
const getTodos = (params = {}, callback) => { const request = new XMLHttpRequest(); request.addEventListener('readystatechange', () => { if(request.readyState === 4 && request.status === 200){ const data = JSON.parse(request.responseText); callback(undefined, data); } else if(request.readyState === 4){ callback('could not fetch data', undefined); } }); // 拼接查询参数 let baseUrl = 'https://my-json-server.typicode.com/nebojsazr/todo_service/todos/'; const queryArr = []; for(const key in params) { if(params[key]) { // 跳过空值参数 queryArr.push(`${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`) } } if(queryArr.length) { baseUrl += `?${queryArr.join('&')}` } request.open('GET', baseUrl); request.send(); }; // 渲染数据的公共方法 const renderTodos = (data) => { document.getElementById('list').innerHTML = JSON.stringify(data, undefined, 2); } // 页面加载先拉全量数据 getTodos({}, (err, data) => { if(err){ console.log('cb fired') } else { renderTodos(data) } }); // 绑定表单提交事件 document.getElementById('fForm').addEventListener('submit', (e) => { // 阻止默认表单提交刷新页面 e.preventDefault(); // 获取表单值 const titleLike = document.querySelector('input[name="title_like"]').value.trim(); const action = document.querySelector('select[name="action"]').value.trim(); // 带参数请求过滤后的数据 getTodos({ title_like: titleLike, action: action }, (err, data) => { if(err){ console.log('cb fired') } else { renderTodos(data) } }) })
实现说明
- 表单提交时会自动跳过空值的过滤条件,只传有值的参数给接口
- 模糊匹配的逻辑直接由json-server实现,无需前端手动过滤全量数据
- 如果不想每次过滤都请求接口,也可以在拿到全量数据后存在变量里,表单提交时用
filter方法手动筛选内存中的数据即可
内容的提问来源于stack exchange,提问作者rookie257
相关产品推荐
相关产品推荐

