zoukankan      html  css  js  c++  java
  • node.js关于传送数据的二三事

    配置好node环境后

    书写代码

    目录结构:

    代码:

     1 <!DOCTYPE html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <title>Title</title>
     6     <script src="jquery-1.10.2.min.js"></script>
     7 </head>
     8 <body>
     9 <input id="name" type="text">
    10 <div id="container"></div>
    11 <button id="btn">提交</button>
    12 <script src="main.js"></script>
    13 </body>
    14 </html>

    main.js

     1 (function () {
     2 
     3     $("#btn").click(function () {
     4         $.post("/test",{
     5             name:$("#name").val()
     6         }).done(function (data) {
     7             $("#container").html(data.name);
     8         }).fail(function () {
     9             console.log("位置错误");
    10         })
    11     });
    12 
    13 
    14 })();

    index.js

    var express = require('express');
    var router = express.Router();
    
    /* GET home page. */
    router.get('/', function(req, res, next) {
      res.render('index', { title: 'Express' });
    });
    
    router.post("/test",function (req, res, next) {
      res.json({name:req.body.name});
    });
    
    module.exports = router;

    自己理解:

      数据传递过程,点击按钮后,input数据传入name空间内,index中通过req.body获取(如果是gei则用req.query获取),在经res传送给main,main中的data就是返回来的json数据。

    注意点:

      一、保证是一个服务器,如/test

      二、res不只有json,还有jsonp,render,send,其中send还可以发送html标签,render主要是把数据传递给views中的ejs文件用

      三、module.exports 的意思同window.name=window.name||{},意思把函数公开到外界

      四、注意index中的next,意思是它可以接受很多的post

  • 相关阅读:
    nmon监控及分析(转)
    Python资源大全
    pyqt4使用简易笔记
    windows下 使用pyinstaller 打包os.Popen()问题
    用pyautogui操作windows
    jmeter 报错:java.net.BindException: Address already in use: connect
    jmeter 报错Non HTTP response code: org.apache.http.conn.ConnectTimeoutException
    vue父子组件通信
    centos6.7安装mysql-5.7
    linux下 多python环境 修改默认python2为python3
  • 原文地址:https://www.cnblogs.com/chenluomenggongzi/p/6040528.html
Copyright © 2011-2022 走看看