我正在使用 node.js 创建一个应用程序,该应用程序维护课程及其各自的讲座和幻灯片的存储库。并且学生的课程(来自mysql Db)的检索是基于学生姓名,讲座的检索是基于课程名称等等。学生姓名存储在服务器上,我必须在调用服务器获取课程列表之前获取它。
这是我的代码,有更多解释:
var StdName;
$(document).ready(function () {
//connect to server
connectBind();
var socket = $("#click").data();
/**********Query database For student name!!!**********/
try {
socket.emit('askStdName');
}
catch (err) {
alert(err.message);
}
/********Query database For Courses!!!************/
try {
socket.emit('view-contents', StdName);
}
catch (err) {
alert(err.message);
}
});
//connecting to server
function connectBind() {
// connect to server on this port.
var socket = io.connect('http://localhost:3000');
$("#click").data(socket);
/**********GETTING NAME OF STUDENT*********/ //I WANT TO GET STUDENT NAME BEFORE THE QUERY FOR COURSES GET CALLED
try {
socket.on('get-Studentname', function (data) {
StdName = data;
alert("StdName: " + StdName);
});
}
catch (err) {
alert(err.Message);
}
这是服务器端脚本:
var express = require('express'); //load express
var http = require('http'); // then http
var socketIO = require('socket.io'); // then socket
var mysql = require('mysql');
var nodemailer = require("nodemailer");
var client = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'smartboard_db'
});
client.connect();
var app = express(); // create application
var server = http.createServer(app); //create server
var io = socketIO.listen(server); // start listening to server.
io.set('log level', 2);
// setup routing for static files.
app.use(express.static(__dirname + '/public'));
//start server
server.listen(3000, function(){
console.log('Server running...');
});
// First page
app.get('/', function(request, response) {
response.sendfile(__dirname + '/student-home.html');
});
io.set('log level', 1);
io.sockets.on('connection', function (socket) {
var sucess;
console.log("client connected");
/************SENDING THE NAME TO CLIENT*************/
socket.on('askStdName', function () {
console.log('sending student name to client');
socket.emit('get-Studentname', stdName);
});
/***********CHANNEL FOR GETTING COURSE LIST************/
socket.on('view-contents', function (stdName) {
//console.log("this is what I get from client for courses: " + stdName);
var DATABASE = 'smartboard_db';
client.query('USE ' + DATABASE);
/*****QUEURY FOR COURSES *****************/
client.query('SELECT courses FROM student_info WHERE name = "' + stdName + '"', function (err, results) {
if (err) {
throw err;
}
else {
console.log(JSON.stringify({ courses: results }));
socket.emit('courses', JSON.stringify({ courses: results }));
}
});
});
});
任何人都可以帮忙吗?