在 加载数据 章节中,我们了解了如何将数据从服务器传输到浏览器。有时你需要以相反的方向发送数据,这就是 <form>
(Web 平台提交数据的方式)的用武之地。
¥In the chapter on loading data, we saw how to get data from the server to the browser. Sometimes you need to send data in the opposite direction, and that’s where <form>
— the web platform’s way of submitting data — comes in.
让我们构建一个待办事项应用。我们已经在 src/lib/server/database.js
中设置了一个内存数据库,并且我们在 src/routes/+page.server.js
中的 load
函数使用 cookies
API,以便我们可以拥有每个用户的待办事项列表,但我们需要添加 <form>
来创建新的待办事项:
¥Let’s build a todo app. We’ve already got an in-memory database set up in src/lib/server/database.js
, and our load
function in src/routes/+page.server.js
uses the cookies
API so that we can have a per-user todo list, but we need to add a <form>
to create new todos:
<h1>todos</h1>
<form method="POST">
<label>
add a todo:
<input
name="description"
autocomplete="off"
/>
</label>
</form>
<ul class="todos">
如果我们在 <input>
中输入一些内容并按 Enter,浏览器会向当前页面发出 POST 请求(因为 method="POST"
属性)。但这会导致错误,因为我们尚未创建服务器端操作来处理 POST 请求。我们现在就这么做:
¥If we type something into the <input>
and hit Enter, the browser makes a POST request (because of the method="POST"
attribute) to the current page. But that results in an error, because we haven’t created a server-side action to handle the POST request. Let’s do that now:
import * as db from '$lib/server/database.js';
export function load({ cookies }) {
// ...
}
export const actions = {
default: async ({ cookies, request }) => {
const data = await request.formData();
db.createTodo(cookies.get('userid'), data.get('description'));
}
};
request
是标准 请求 对象;await request.formData()
返回一个 FormData
实例。
¥The request
is a standard Request object; await request.formData()
returns a FormData
instance.
当我们按下 Enter 键时,数据库会更新,页面会重新加载新数据。
¥When we hit Enter, the database is updated and the page reloads with the new data.
请注意,我们不必编写任何 fetch
代码或类似的东西 — 数据会自动更新。因为我们使用的是 <form>
元素,所以即使 JavaScript 被禁用或不可用,此应用也能正常运行。
¥Notice that we haven’t had to write any fetch
code or anything like that — data updates automatically. And because we’re using a <form>
element, this app would work even if JavaScript was disabled or unavailable.
<script>
let { data } = $props();
</script>
<div class="centered">
<h1>todos</h1>
<ul class="todos">
{#each data.todos as todo (todo.id)}
<li>
{todo.description}
</li>
{/each}
</ul>
</div>
<style>
.centered {
max-width: 20em;
margin: 0 auto;
}
label {
width: 100%;
}
input {
flex: 1;
}
span {
flex: 1;
}
button {
border: none;
background: url(./remove.svg) no-repeat 50% 50%;
background-size: 1rem 1rem;
cursor: pointer;
height: 100%;
aspect-ratio: 1;
opacity: 0.5;
transition: opacity 0.2s;
}
button:hover {
opacity: 1;
}
.saving {
opacity: 0.5;
}
</style>