基于express框架的Node.js ajax mongoose实时查询操作
发布于 10 年前 作者 kingche 4491 次浏览 最后一次编辑是 8 年前

想实现选取下拉框后,后台实时查询相关数据,并返回前端显示 前端index.ejs <!DOCTYPE html> <html> <head> <meta charset=“UTF-8” /> <title><%= title %></title> <link rel=‘stylesheet’ href=’/stylesheets/style.css’ /> <script src="/javascripts/jquery-2.1.1.min.js"></script> <script type=“text/javascript”> function showCustomer(str) { var xmlhttp;
if (str=="") { document.getElementById(“txtHint”).innerHTML=""; return; } if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp = new ActiveXObject(“Microsoft.XMLHTTP”); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState ==4 && xmlhttp.status == 200) { document.getElementById(“txtHint”).innerHTML = xmlhttp.responseText; } } xmlhttp.open(“GET”,"/public/javascripts/func.js?q="+str,true); xmlhttp.send(); } </script> </head> <body> <p><%= title %></p> <form action="" style=“margin-top:15px;”> <label>请选择一个群组: <select name=“groupname” onchange=“showCustomer(this.value)” style=“font-family:Verdana, Arial, Helvetica, sans-serif;”> <option value=“baidu”>BAIDU</option> <option value=“tencent”>TENCENT</option> <option value=“ali”>ALI</option> </select> </label> </form> <div id=“txtHint”>群组信息将在此处列出 …</div> </body> <script type=“text/javascript” src="/javascripts/func.js"></script> </html>

查询功能/public/javascripts/func.js var mongoose = require(‘mongoose’) ; var models = require(’./models.js’) ; var GroupModel = models.Group ; mongoose.connect(‘mongodb://localhost/mytest’) ; var getinfo = function(req,res){ var name = req.query.q; GroupModel.find({groupname:name},function(err,doc){ if(doc != 0){ console.log(‘ooooooo’);//用于测试该函数是否被调用 res.write(doc[0].descriptions); } }); }; getinfo();

控制台输出 Express server listening on port 3000 GET / 304 21ms GET /stylesheets/style.css 304 8ms GET /javascripts/jquery-2.1.1.min.js 304 8ms GET /javascripts/func.js 200 12ms - 1006b GET /public/javascripts/func.js?q=baidu 404 2ms 还是没有反应了,也就是func.js并未被调用 请问:node怎么和ajax结合?

1 回复
回到顶部