编写html
<form action="" id="formBtn">
username:<input type="text" name="username"/>
password:<input type="password" name="pwd"/>
<input type="button" value="submit" id="btn"/>
</form>
<div id="item"></div>
使用jQuery发送ajax请求
<script src="http://cdn.bootcss.com/jquery/2.2.1/jquery.js"></script>
<script>
//获取按钮和表单
var $btn = $('#btn'),
$formBtn = $('#formBtn');
//给按钮添加点击事件
$btn.on('click',function(){
//发送ajax
$.ajax({
url: "http://localhost:3000/reg",
type: 'POST',
data: $formBtn.serialize(),
dateType: 'text',
success: function(data){
$('#item').html(JSON.parse(data).msg );
}
})
})
</script>
安装数据库之后打开命令行创建表
show databases; //查看表
create table user(number INT(11),username varchar(32),pwd varchar(32)); //创建表
select * from user //查看user表
并且需要在该项目文件夹下:npm install mysql
模拟后台编写js
var http = require('http');var url = require('url');
var fs = require('fs');var mysql = require('mysql');
var qs = require('querystring');
var connection = mysql.createConnection({
host: 'localhost',
port: '3306',
user: 'root',
password: '123456',
database: 'test'
});
var server = http.createServer(function(req,res){
var urlObj = url.parse(req.url,true);
var pathname = urlObj.pathname;
res.writeHead(200,{"Access-Control-Allow-Origin":"*"});
if('/' == pathname){
fs.readFile('./reg.html', function(err,data){
res.end(data);
});
}else if('/reg' == pathname){
//每当服务器接收到客户端发送过来的数据时候 会出发事件
var ret = '';
req.on('data', function(data){
console.log(data.toString);
ret += data.toString();
});
//接收完毕的时候触发end事件 请求体的数据就是接收完整了
req.on('end', function(){
//{email:'cjj@sina.com', pwd:'123456'}
ret = qs.parse(ret);
console.log(ret);
var sql = "insert into user(id,username,pwd) values(null,'" + ret.username + "','" + ret.pwd + "')";
connection.query(sql, function(err,ret){
if(err){
return console.log(err);
}else{
//当注册成功后返回这个
res.end('{"msg":"register success!!!!!"}');
}
});
});
}
});
server.listen(3000, 'localhost',function(){
console.log('server running on localhost:3000');
});
运行改文件即可。