码迷,mamicode.com
首页 > 数据库 > 详细

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

时间:2018-12-25 14:31:07      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:put   dev   post   inner   requested   doctype   -o   title   text   

很多小白不知道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 &gt;= 200 &amp;&amp; xhr.status &lt; 300) || xhr.status == 304) {
      console.log(xhr.responseText)
      var data = JSON.parse(xhr.responseText)
      var str = ‘‘
      for(var i = 0; i &lt; data.length; i ++) {
        str += "&lt;div&gt;name: " + data[i].name + "&lt;/div&gt;&lt;div&gt;price: " + data[i].price + "&lt;/div&gt;"
      }
      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页面就能拿到数据了~

来源:https://segmentfault.com/a/1190000016700988

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

标签:put   dev   post   inner   requested   doctype   -o   title   text   

原文地址:https://www.cnblogs.com/qixidi/p/10173624.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!