前台提交数据到node服务器(get方式)

、有两种办法,一种是表单提交,一种是ajax方式提交。

1、form提交

   在前台模板文件上写:

1 <form action="/reg" method="get">
2     <input type="text" />
3     <input type="password" />
4     <input type="submit" />
5 </form

   index.js添加一个路由规则:

 1 router.get('/reg',(req,res) => {
 2     //req,浏览器发送给服务器的数据保存在这里
 3     //参数1:数据库代码  参数2:动态值  参数3:回调
 4     sql('insert into `user` (`id`,`username`,`password`) values (0,?,?)',[req.query.name,req.query.password],(err,result) => {
 5         if(err){
 6             console.log('[INSERT ERROR] - ',err.message);
 7             return;
 8         }
 9         res.json({
10             success : '[INSERT SUCCESS] - '
11         });
12     });
13 });

2、ajax提交

  (1)先引入jQuery;

    (2)前台模板文件写:

 1     <input type="text" name="name" class="name" />
 2     <input type="password" name="password" class="psw" />
 3     <input type="submit" class="submit" />
 4     <script src="/jquery.js"></script>
 5     <script>
 6         $('.submit').click(function () {
 7             $.ajax({
 8                 url : '/reg',
 9                 type : 'get',
10                 data : {
11                     name : $('.name').val(),
12                     password : $('.psw').val()
13                 },
14                 success : function (data) {
15             console.log(data);
16                 }
17             });
18         });
19     </script>

 

posted @ 2017-04-19 22:31  小小lomo  阅读(279)  评论(0编辑  收藏  举报