我正在制作一个网站,需要在单击按钮时更改嵌入视频。我的html页面加载一个js脚本,该脚本需要调用数据库中用node.js编码的函数。整个事情都在 mongoDB 服务器上运行,并有 mongoose 来支持我。为了让事情更清楚,这里有一些代码:
我的数据库(仅相关功能):
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;
现在我需要通过我的 html 页面调用一个能够调用 getSongById(someID) 的脚本。我应该如何做知道我不能要求(数据库),因为要求是基于 Node 和服务器的。另外,由于 getSongById(someID) 由于保存调用而异步,我如何确保返回值不为空?我需要超时几秒吗?
脚本文件需要像这样,并且 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);
}
感谢您的帮助!
最佳答案
在 Node 中创建到 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()
函数修改为异步函数,例如:
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>
关于javascript - 在我的 html 中使用 Node 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36694442/