Express的Ajax實踐

Cacra發表於2018-07-28

對於Ajax一直理解不是很深,正好這次需要用到,做個記錄。

首先的前端程式碼 :

<!DOCTYPE html>
<html>
<head>
  <title><%= title %></title>
  <link rel='stylesheet' href='/stylesheets/style.css' />
  <!-- 引入jquery.js -->
  <script src="javascripts/jquery-3.1.1.min.js"></script>
  <!-- 引入echarts.js -->
  <script src="javascripts/echarts.min.js"></script>
</head>
<body>

  <h1><%= title %></h1>

  <p>Welcome to <%= title %></p>
  <input type="text" value="5000">
  <button class="button">點選傳送</button>
  <div class="div01">

  </div>


  <script type="text/javascript">

     $('.button').on('click',function (e) {
         var txt = $('input').val();
         $.ajax({
             url:'/test',
             type:'get',
             data:{name:txt},
             dataType:'json',
             success:function (result) {
                 alert('傳輸成功');
                 $('.div01').html(result.tips)
             },
             error:function (msg) {
                 alert('系統發生錯誤');
             }
         })
     })

  </script>

</body>
</html>

後端進行接收和處理:

var express = require('express');
var router = express.Router();

var submessage = '';

// 匯入mysql模組
var mysql = require('mysql');


// 連線到mysql
var connection = mysql.createConnection({      //建立mysql例項
    host:'127.0.0.1',
    port:'3306',
    user:'root',
    password:'',
    database:'test'
});
connection.connect();
var sql = 'SELECT * FROM tvalues';
var str = " ";
connection.query(sql, function (err,result) {
    if(err){
        console.log('[SELECT ERROR]:',err.message);
    }
    str = JSON.stringify(result);
    //資料庫查詢的資料儲存在result中,但瀏覽器並不能直接讀取result中的結果,因此需要用JSON進行解析
    //console.log(result);   //資料庫查詢結果返回到result中
    console.log(str);
});


/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: str });
});

router.get('/test',function (req,res) {

    //接收傳過來的資料
    var name = req.query.name;


    /*接收MQTT協議資料*/
    var mqtt = require('mqtt')
    var fs = require('fs')

    var client  = mqtt.connect('mqtt://127.0.0.1:61613',{username:"admin",password:"password"})

    client.on('connect',function () {
        //把頁面輸入的name資料,作為時間間隔,傳輸給MQTT伺服器。
        client.subscribe('world');
        client.publish('world',name);
    })

    client.on('message', function (topic, message) {

      console.log(typeof message);
      submessage = message.toString();
      console.log(message.toString());
      client.end();

    })

    var ajaxTest = {
        tips:name
    };

    res.send(ajaxTest);
})

connection.end();

module.exports = router;

這次只是使用了get的請求方法。

參考文章:

https://www.zhihu.com/question/28470466
https://www.cnblogs.com/xuange306/p/5975828.html
https://blog.csdn.net/cdnight/article/details/50857586
https://cnodejs.org/topic/50d01507637ffa4155a9f359
https://blog.csdn.net/u012251421/article/details/49493561
http://www.w3school.com.cn/jquery/ajax_post.asp
https://www.cnblogs.com/yoyotl/p/5091888.html
https://blog.csdn.net/educast/article/details/72724368
http://www.runoob.com/nodejs/nodejs-mysql.html
https://www.cnblogs.com/zhuzhenwei918/p/7252602.html

Express會話控制:https://blog.csdn.net/mutouafangzi/article/details/77533002

相關文章