藉助node.js + mysql 學習基礎ajax~
阿新 • • 發佈:2018-12-25
很多小白不知道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頁面就能拿到資料了~