環境要求是安裝node~javascript
先上linkMysql.jshtml
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,用了原生寫法,具體的就不講了百度一大堆~java
<!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頁面就能拿到數據了~node