码迷,mamicode.com
首页 > 其他好文 > 详细

node服务器获取form表单

时间:2016-10-15 11:27:55      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

搭建好服务器后

(前言,本文只是介绍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>标签中。(处理的是文件

node服务器获取form表单

标签:

原文地址:http://www.cnblogs.com/chenluomenggongzi/p/5962775.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!