搭建好服務器后
(前言,本文只是介紹form表單直接提供給 本頁面數據,即在不刷新頁面的前提下更改數據)
在public里面添加index.html
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <script src="node_modules/jquery/dist/jquery.min.js"></script> 7 </head> 8 <body> 9 <form method="post" action="hello"> 10 <label> 11 name: 12 <input type="text" name="name" required="required"> 13 </label> 14 <input type="submit" value="submit"> 15 </form> 16 <div id="result"></div> 17 <script src="main.js"></script> 18 </body> 19 </html>
在新建個main.js
1 (function () { 2 3 $("form").on("submit", function (e) { 4 e.preventDefault(); 5 6 // console.log(this["name"].value, this.action, this.method); 7 8 $.post(this.action, {name: this["name"].value}).done(function (data) { 9 $("#result").html(data); 10 }).fail(function (err) { 11 alert("無法連接服務器"); 12 }); 13 }); 14 15 })();
在routes里面的index文件中添加如下代碼
1 router.post("/hello", function (req, res) { 2 res.render("hello", {name: req.body.name}); 3 });
再在views文件夾下添加hello.jade文件
1 html 2 head 3 title = "hello" 4 body 5 div hello #{name};
ok,運行即可
補充一下,send和render的區別
send:直接處理數據,作用:把數據傳到<body>標簽中,只能傳來get,即傳過來搜索框中的內容(處理的是直接的數據)
render:意為渲染,作用,把一個文件渲染后,傳到<body>標簽中,使用post處理過得數據,傳送給那個文件,后在傳到<body>標簽中。(處理的是文件)