如今,我們經常使用複雜的框架和工具鏈來建立互動式表單 - 但是如果我們告訴您,無需編寫一行傳統 JavaScript 邏輯就可以建立智慧、動態的表單呢?
在本文中,我們將向您展示如何使用HMPL (一種簡化客戶端與伺服器互動的輕量級模板引擎)建立非同步提交的功能齊全的表單。
開始吧!
我們將使用一個簡單的資料夾佈局:
📁 smart-form
├── 📁 components
│ └── 📁 Register
│ └── index.html
├── 📁 src
│ ├── global.css
│ ├── global.js
│ └── index.html
├── app.js
└── routes
└── post.js
伺服器:純 HTML、CSS 和 HMPL 範本。
客戶端:Node.js + Express 接收表單資料。
沒有像 React、Vue 甚至 jQuery 這樣的框架。只需清理 Web API 和聲明邏輯。
讓我們從基本風格開始。
src/global.css
body {
font-family: Arial, sans-serif;
background: #f4f4f4;
padding: 50px;
}
form {
background: white;
padding: 20px;
border-radius: 6px;
box-shadow: 0 4px 10px rgba(0,0,0,0.1);
max-width: 400px;
margin: auto;
}
.form-example {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
}
input[type="text"],
input[type="password"] {
width: 100%;
padding: 8px;
box-sizing: border-box;
}
input[type="submit"] {
background-color: #649606;
color: white;
border-radius: 5px;
padding: 10px 15px;
cursor: pointer;
}
我們將設定一個簡單的 Express 伺服器,其中包含一個 POST 路由來處理我們的表單提交。
應用程式.js
const express = require("express");
const path = require("path");
const cors = require("cors");
const app = express();
const PORT = 8000;
app.use(cors());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(express.static(path.join(__dirname, "src")));
const postRoutes = require("./routes/post");
app.use("/api", postRoutes);
app.get("/", (_, res) => {
res.sendFile(path.join(__dirname, "src/index.html"));
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
路線/post.js
const express = require("express");
const router = express.Router();
router.post("/register", (req, res) => {
const { login, password } = req.body;
if (!login || !password) {
return res.status(400).send("<p style='color: red;'>Missing fields!</p>");
}
console.log("User Registered:", login);
res.send(`<p style='color: green;'>Welcome, ${login}!</p>`);
});
module.exports = router;
這就是奇蹟發生的地方。此表單將使用 HMPL 的request
區塊提交資料,無需您編寫任何 JavaScript 事件監聽器。
元件/註冊/index.html
<div>
<form onsubmit="function prevent(e){e.preventDefault();};return prevent(event);" id="form">
<div class="form-example">
<label for="login">Login:</label>
<input type="text" name="login" id="login" required />
<br/>
<label for="password">Password:</label>
<input type="password" name="password" id="password" required />
</div>
<div class="form-example">
<input type="submit" value="Register!" />
</div>
</form>
<p>
{{#request
src="/api/register"
after="submit:#form"
repeat=false
indicators=[
{
trigger: "pending",
content: "<p>Loading...</p>"
}
]
}}
{{/request}}
</p>
</div>
這裡發生了什麼事?
onsubmit
阻止預設行為。
{{#request}}
擷取表單提交事件。
after="submit:#form"
定義何時觸發請求。
indicators
顯示載入狀態或回饋。
無需手動fetch
,無需非同步/等待。一切都已宣布。
現在,讓我們使用 HMPL 在我們的頁面上動態呈現這個元件。
src/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Smart Form</title>
<link rel="stylesheet" href="global.css" />
</head>
<body>
<div id="wrapper"></div>
<script src="https://unpkg.com/json5/dist/index.min.js"></script>
<script src="https://unpkg.com/dompurify/dist/purify.min.js"></script>
<script src="https://unpkg.com/hmpl-js/dist/hmpl.min.js"></script>
<script>
import { compile } from "hmpl-js";
const templateFn = compile(`
{{#request src="/components/Register/index.html"}}{{/request}}
`);
const obj = templateFn();
document.getElementById("wrapper").append(obj.response);
</script>
</body>
</html>
或者,如果您喜歡模組化,您可以將此邏輯分解到單獨的
global.js
檔案中。
您將獲得以下內容:
簡潔、時尚的表單
僅使用 HTML + HMPL 進行非同步提交
驗證和回饋—無需自訂 JS 邏輯
無需 JavaScript 框架:無需 React,無需 Angular。
聲明性邏輯:描述應該發生什麼,而不是如何發生。
簡單且可擴展:非常適合登陸頁面、管理工具和 MVP。
您甚至可以擴展此模式以支援多步驟表單、載入器、錯誤處理或
repeat
間隔的自動保存。
建立互動式 Web 表單不再需要 JavaScript 膨脹或龐大的工具鏈。使用HMPL ,您可以保持程式碼乾淨、語義化且功能強大 - 非常適合喜歡聲明式邏輯和簡單性的開發人員。
如果您喜歡這篇文章,請考慮給 HMPL 一顆星! ❤️
{% cta https://github.com/hmpl-language/hmpl %} 💎 在 GitHub 上為 HMPL 讚 {% endcta %}
感謝您的閱讀,祝您編碼愉快!
原文出處:https://dev.to/hmpljs/create-smart-forms-without-javascript-the-magic-of-html-and-ajax-i29