Node.js 的 30 天學習日記--第二十三天

Node.js 學習第二十三天

還有一個禮拜就三十天了,真的會趕不上啊,玩樂時間太多了XDDD

如果在看的過程中有任何錯誤歡迎寫 E-MAIL: pp840405@gmail.com 提醒我錯誤。


POST AJAX 前後端介接原理

用 AJAX 的方式讓前端要到資料後不用換頁就能顯示資料

  1. 新增一個 post 的 /searchAJAX 路由

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    var express = require('express');
    var app = express();
    var engine = require('ejs-locals');
    //取得 body-parser 套件
    var bodyParser = require('body-parser')
    app.engine('ejs',engine);
    app.set('views','./views');
    app.set('view engine','ejs');
    app.use(express.static('public'));
    // body 解析
    //內容支援JSON格式
    app.use(bodyParser.json());
    //解析表單內容({物件設定})
    app.use(bodyParser.urlencoded({extended:false}));
    app.get('/',function(req,res){
    res.send('你進入到首頁');
    console.log('有人造訪首頁')
    });
    //新增搜尋頁 讀取search.ejs
    app.get('/search',function(req,res){
    res.render('search');
    });
    app.post('/searchList',function(req,res){
    console.log(req.body);
    res.redirect('search');
    });
    app.post('/searchAJAX',function(req,res){
    console.log(req.body);
    res.send('hello!!');
    });

    //監聽 port
    var port = process.env.PORT || 3000;
    app.listen(port);
  2. 把 search.ejs 改成這樣

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    </head>
    <body>
    <!-- 資料移動到/searchList路由上 用post方式 -->
    <form action="/searchList" method="post">
    <input type="text" name="content" id="content" value="">
    <input type="submit" id="send" value="送出">
    </form>
    <script src="/js/all.js"></script>
    </body>
    </html>
  3. 在 public 資料夾裡面新增一個 js 資料夾在裡面又新增一個 all.js 檔案。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    //抓DOM元素
    var send = document.getElementById('send');
    var content = document.getElementById('content');

    send.addEventListener('click',function(e){
    e.preventDefault();
    //撈content值
    var str = contet.value;
    //開啟XML設定
    var xhr = new XMLHttpRequest();
    //POSY模式 指定/searchAJAX路由
    xhr.open('post','/searchAJAX');
    //傳送格式
    xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
    //組合字串
    var data = 'content='+ str;
    //傳送資料
    xhr.send(data);
    //console看資料
    xhr.onload = function(){
    console.log(xhr.responseText);
    }
    })

結語

有任何問題歡迎寫 MAIL: pp840405@gmail.com 一起共同討論。