server.js
var http = require(‘http’);
var server = http.createServer(function (req, res) {
var body = ‘’;
req.on('data', function(data) { // 接收客户端发送过来的数据, 也就是 xmlHttp.send(value);
if(data==resultdata[0])
{
body += data;
}
});
req.on('end', function() {
res.writeHeader(200, {
'Content-Type': 'text/plain',
'Access-Control-Allow-Origin': '*' //解决跨域问题
});
res.write("hello:" + body);
res.end();
})
});
server.listen(3000, function () {
console.log(‘server start at localhost:3000’);
});
var mysql = require(‘mysql’);
var connection = mysql.createConnection({
host : ‘localhost’,
user : ‘root’,
password : ‘yqf19980217’,
port: ‘3306’,
database: ‘test’
});
connection.connect();
var resultdata =[] ;
var sql = ‘SELECT * FROM websites’;
connection.query(sql,function (err, result) {
if(err){
console.log(’[SELECT ERROR] - ',err.message);
return;
}
for (var i = result.length - 1; i >= 0; i–) {
resultdata[i] = result[i].name;
}
console.log('--------------------------SELECT----------------------------');
console.log(resultdata[0]);
console.log('------------------------------------------------------------\n\n');
});
connection.end();
index.html
Document 提交我是返回的数据:
index.jsvar test = document.getElementById(‘test’);
var bt = document.getElementById(‘bt’);
bt.onclick = function () {
var value = document.getElementById(‘username’).value;
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange=function()
{
if (xmlHttp.readyState4 && xmlHttp.status200)
{
test.innerHTML = xmlHttp.responseText;
}
};
xmlHttp.open('POST', 'http://127.0.0.1:3000/', true);
xmlHttp.send(value); //吧input框中的value发送过去
};