如何在SvelteKit的load函数中利用actions变量过滤数据库查询结果?
服务端过滤load函数返回数据的实现方法
因为actions和load是独立执行的服务端函数,没法直接共享变量,所以得通过Cookie或者URL查询参数这类方式把过滤参数传递给load,再在load里完成数据过滤。以下是两种可行的方案:
方案一:用Cookie传递过滤参数
把actions中获取到的lastname存入Cookie,load读取Cookie后过滤数据:
import { error, redirect } from '@sveltejs/kit'; export const actions = { default: async ({ request, cookies }) => { const data = await request.formData(); const ln = data.get('lastname'); // 将过滤参数存入Cookie,配置安全选项 cookies.set('filter_lastname', ln, { path: '/', maxAge: 86400, // 有效期1天 httpOnly: true, // 仅服务端可访问,提升安全性 secure: process.env.NODE_ENV === 'production' }); // 重定向回当前页面,触发load重新拉取过滤后的数据 throw redirect(303, '/'); } }; export function load({ cookies }) { if (!db) throw error(404); const filterLastname = cookies.get('filter_lastname'); let todos = db.getTodos(); // 有过滤参数时执行服务端过滤 if (filterLastname) { todos = todos.filter(todo => todo.lastname === filterLastname); } return { todos }; }
方案二:用URL查询参数传递过滤参数
提交表单后重定向到带查询参数的URL,load读取URL参数过滤数据,这种方式支持书签分享过滤状态:
import { error, redirect } from '@sveltejs/kit'; export const actions = { default: async ({ request }) => { const data = await request.formData(); const ln = data.get('lastname'); // 重定向到带查询参数的当前页面,注意编码特殊字符 throw redirect(303, `/?lastname=${encodeURIComponent(ln)}`); } }; export function load({ url }) { if (!db) throw error(404); const filterLastname = url.searchParams.get('lastname'); let todos = db.getTodos(); if (filterLastname) { todos = todos.filter(todo => todo.lastname === filterLastname); } return { todos }; }
注意事项
- 两种方案都是在服务端完成过滤,不会把全量数据发送到前端,完全符合你的需求。
- 如果需要清空过滤条件,只需清除对应Cookie或者移除URL中的查询参数即可。
- 记得对用户输入的
lastname做校验,比如空值判断、特殊字符过滤,避免潜在的安全风险(比如SQL注入,若使用SQL数据库)。
内容的提问来源于stack exchange,提问作者KeesdeB
相关产品推荐
相关产品推荐

