页面代码:
<!DOCTYPE html> <html lang="utf-8"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <head> <title>Put data to db</title> </head> <body> <form id="form1"> 用户名:<input type="text" id="username" name="name" value=""><br/> 密码 :<input type="password" id="userpswd" name="pswd" value=""><br/> <input type="button" value="提交" onclick="submitData();"/> </form> </body> </html> <script type="text/javascript"> <!-- function submitData(){ var obj={ name:document.getElementById("username").value, password:document.getElementById("userpswd").value }; var xhr=new XMLHttpRequest(); xhr.open('put','index.html',true); xhr.onload=function(e){ if(this.status==200){ alert(this.response); } }; xhr.send(JSON.stringify(obj)); } //--> </script>
后台代码:
'use strict'; var express=require('express'); var http=require('http'); var fs=require('fs'); var querystring=require('querystring'); var app=express(); var mysql=require('mysql'); var pool=mysql.createPool({ host:'127.0.0.1', port:'3306', database:'test', user:'root', password:'12345678', }); app.get('/index.html',function(req,rsp){ //rsp.writeHead(200,{'Content-Type':'text/html'}); //fs.createReadStream('index.html').pipe(rsp); rsp.sendFile(__dirname+'/index.html');// 与上两句意义相同 }); app.put('/index.html',function(req,res){ req.on('data',function(data){ var obj=JSON.parse(data.toString());// 取得Ajax提交的参数 console.log(obj); pool.getConnection(function(err,connection){ if(err){ res.send('Can not connect to MySql DB'); console.log(err); }else{ var str; connection.query('insert into emp set ?',{name:obj.name,password:obj.password},function(err,result){ if(err){ str='Insert failed'; }else{ str="Insert succeed"; } connection.release(); res.send(str); }) } }); }); }); app.listen(8080,"127.0.0.1");