借助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页面就能拿到数据了~
相关推荐
kentrl 2020-11-10
结束数据方法的参数,该如何定义?-- 集合为自定义实体类中的结合属性,有几个实体类,改变下标就行了。<input id="add" type="button" value="新增visitor&quo
ajaxyan 2020-11-09
zndy0 2020-11-03
学留痕 2020-09-20
Richardxx 2020-11-09
learningever 2020-09-19
chongxiaocheng 2020-08-16
ajaxhe 2020-08-16
lyqdanang 2020-08-16
curiousL 2020-08-03
TONIYH 2020-07-22
时光如瑾雨微凉 2020-07-19
83510998 2020-07-18
坚持着执着 2020-07-16
jiaguoquan00 2020-07-07
李永毅 2020-07-05
坚持着执着 2020-07-05