在載入資料章節中,我們了解如何將資料從伺服器傳送到瀏覽器。有時您需要將資料以相反方向傳送,這就是 <form>
的用途 — Web 平台提交資料的方式。
讓我們建立一個待辦事項應用程式。我們已經在 src/lib/server/database.js
中設定了一個記憶體內資料庫,並且在 src/routes/+page.server.js
中的 load
函式使用了 cookies
API,以便我們可以擁有每個使用者的待辦事項列表,但我們需要新增一個 <form>
來建立新的待辦事項
src/routes/+page
<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 請求。現在讓我們執行此操作
src/routes/+page.server
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
是一個標準的 Request 物件;await request.formData()
會傳回一個 FormData
實例。
當我們按下 Enter 鍵時,資料庫會更新,並且頁面會重新載入新的資料。
請注意,我們不必編寫任何 fetch
程式碼或類似的程式碼 — 資料會自動更新。而且由於我們使用的是 <form>
元素,即使 JavaScript 被停用或無法使用,此應用程式仍然可以運作。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<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>