借助node.js + mysql 学习基础ajax~

风吹一个大耳东

很多小白不知道ajax怎么学,所以就弄了个node后台模拟下基本的ajax请求。

环境要求是安装node~

先上linkMysql.js

var mysql = require('mysql')
var connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '', //自己数据库的密码
  database: ''//自己数据库的名称
})

function LinkMysql(tableName, key, value) {
  connection.connect()
  var data = ''
  var sql = 'SELECT * FROM ' + tableName +' where ' + key + '=' + value
  console.log(sql)
  return new Promise(function(resolve,reject) {
    connection.query(sql, function(err, result) {
      console.log('--------------------------SELECT----------------------------');
      console.log(result);
      console.log('------------------------------------------------------------\n\n');  
      resolve(result)
    })
  })
}

function cutMysql() {
  connection.end();
}

module.exports = {
  cutMysql,
  LinkMysql
}

主JS server.js,提供连接maysql和不连接mysql两种版本

var http = require('http')
var url = require('url');
var util = require('util');
var sqlFunc = require('./linkMysql.js');

// 不连接数据库操作
// var tempJson = [{
//   name: '巧克力',
//   price: 10
// },{
//   name: '薯条',
//   price: 20
// }]

http.createServer(function(req, res) {
  // 跨域处理
  res.setHeader("Access-Control-Allow-Origin", "*"); 
  res.setHeader("Access-Control-Allow-Headers", "X-Requested-With");
  res.setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  res.setHeader("X-Powered-By",' 3.2.1');
  res.setHeader("Content-Type", "application/json");

  var reqUrl = req.url
  var mainPath = reqUrl.split('?')[0]
  var reqData = reqUrl.split('?')[1].split('=')

  if (mainPath == '/test') {
    sqlFunc.LinkMysql('goods_info', reqData[0], JSON.stringify(decodeURIComponent(reqData[1]))).then(function(val) {
      console.log('从数据库获取数据' + val)
      sqlFunc.cutMysql();

      res.writeHead(200, {'content-Type': 'text/plain; charset=utf-8'});
      res.end(JSON.stringify(val));
    })
    // 不连接数据库操作
    // res.writeHead(200, {'content-Type': 'text/plain; charset=utf-8'});
    // res.end(JSON.stringify(tempJson));
  } else {
    res.writeHead(404, {'content-Type': 'text/plain; charset=utf-8'});
  }
  

}).listen(3000);

console.log('Server running at http://localhost:3000');

最后就是前端html页面了~test.html,用了原生写法,具体的就不讲了百度一大堆~

<!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>
  <div>数据请求</div>
  <div class="box">

  </div>
  <script>
    var xhr = new XMLHttpRequest()

    xhr.onreadystatechange = function(){
      if (xhr.readyState == 4) {
        if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
          console.log(xhr.responseText)
          var data = JSON.parse(xhr.responseText)
          var str = ''
          for(var i = 0; i < data.length; i ++) {
            str += "<div>name: " + data[i].name + "</div><div>price: " + data[i].price + "</div>"
          }
          document.querySelector('.box').innerHTML = str
        } else {
          console.log("Request was unsuccessful: " + xhr.status)
        }
      }
    }

    xhr.open('get', 'http://localhost:3000/test?name=巧克力', true)
    xhr.send(null)
  </script>
</body>
</html>

命令行输入
node server.js 启动服务 刷新test.html页面就能拿到数据了~

阅读 2.5k

知识点复习
提供一些前端知识的经验总结,个人复习专用,如果帮到你点个赞

钻到底~

400 声望
26 粉丝
0 条评论

钻到底~

400 声望
26 粉丝
文章目录
宣传栏