前端代码:
<!DOCTYPE html> <html lang="utf-8"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <head> <title>get data from db</title> </head> <body> <form id="form1"> 用户名:<input type="text" id="username" name="name" value=""><br/> <input type="button" value="查询" onclick="search();"/> </form> <table border="1"> <tr> <th>Id</th><th>name</th><th>password</th> </tr> <tbody id="mytable"> </tbody> </table> </body> </html> <script type="text/javascript"> <!-- function search(){ var obj={ name:document.getElementById("username").value, }; var xhr=new XMLHttpRequest(); xhr.open('put','index.html',true); xhr.onload=function(e){ if(this.status==200){ var arr=JSON.parse(this.response); updateTable(arr); } }; xhr.send(JSON.stringify(obj)); } function updateTable(arr){ var table=document.getElementById("mytable"); for(var i=table.childNodes.length-1;i>=0;i--){ table.removeChild(table.childNodes[i]); } for(var i=0;i<arr.length;i++){ var emp=arr[i]; var tr=document.createElement("tr"); var td1=document.createElement("td"); td1.appendChild(document.createTextNode(emp.id)); tr.appendChild(td1); var td2=document.createElement("td"); td2.appendChild(document.createTextNode(emp.name)); tr.appendChild(td2); var td3=document.createElement("td"); td3.appendChild(document.createTextNode(emp.password)); tr.appendChild(td3); table.appendChild(tr); } } //--> </script>
运行情况截图:
后端代码:
'use strict'; var express=require('express'); var http=require('http'); var fs=require('fs'); 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.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("select * from emp where name like ? ","%"+obj.name+"%",function(err,result){ if(err){ str='Search failed'; }else{ str="Search succeed"; } console.log(str); console.log("result.length="+result.length); var arr=[]; for (var i=0; i<result.length; i++) { var tmp = result[i]; var emp=new Object; emp.id=tmp['Id']; emp.name=tmp['name']; emp.password=tmp['password']; arr.push(emp); } connection.release(); res.send(JSON.stringify(arr)); }) } }); }); }); app.listen(8080,"127.0.0.1");