在我的HTML中使用节点function

我正在做一个网站,需要改变一个embedded的video,当一个button被点击。 我的html页面加载了一个js脚本,需要在数据库中调用一个被节点编码的函数。 整个事情是运行在一个mongoDB服务器与mongoose来支持我。 为了使事情更清楚一些代码:

我的数据库(只有相关的function):

function database(){ db = mongoose.createConnection(url); songModel = db.model('Song',{id : Number , title : String, artist : String, genre : String, rating : Number, link : String }); //init freeid songModel.count({},function(err, c){ nextFreeId=c; }); }; database.prototype.getNextFreeId = function(){ return nextFreeId; }; database.prototype.getSongById=function(id2){ songModel.findOne({id : id2}, function(err,obj){ if (err) { console.log('Not Found, error: '+err); return null; } else if (obj) { console.log('Found:', obj); return obj; } }); }; module.exports = database; 

现在我需要通过我能够调用getSongById(someID)的html页面调用一个脚本。 我应该如何做,知道我不能要求(数据库),因为需求是基于节点和服务器。 另外因为getSongById(someID)是asynchronous的,因为保存调用我如何确保返回值不为空? 我需要超时几秒吗?

脚本文件需要像这样的HTML页面加载getRandomVideo():

 var db=require('./module/database'); function getRandomVideo(){ console.log('random video method called'); var numberOfSongs = db.getNextFreeId()-1; idToGet=Math.floor(Math.random() * numberOfSongs); var song = db.getSongById(idToGet); document.getElementById('myVideo').src = song.link; console.log('found random song: '+ song); } 

感谢您的帮助!

在节点中创build一个到getSongById()函数的路由,然后从你的html文件向这个URL发出一个ajax请求。

比方说,在你的app.js中,有这样的东西:

 app.get('/random-video', function(req, res) { console.log('random video method called'); var numberOfSongs = db.getNextFreeId()-1; idToGet=Math.floor(Math.random() * numberOfSongs); db.getSongById(idToGet, function(err, song){ console.log('found random song: '+ song); res.send(JSON.stringify(song)); }); }); 

你还必须修改你的getSongById()函数是asynchronous的,比如:

 database.prototype.getSongById=function(id2, cb){ songModel.findOne({id : id2}, function(err,obj){ if (err) { console.log('Not Found, error: '+err); cb(err); } else if (obj) { console.log('Found:', obj); cb(null, obj); } }); }; 

然后,在你的html页面,一旦你有jQuery加载,做一些事情:

 <script> $(document).ready(function(){ $.ajax({ url: '/random-video', contentType: 'application/json; charset=utf-8', }).done(function(song){ //do stuff with the song }); }) </script>