Node.js---以Ajax方式向后台传递参数

html代码:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="javascripts/jquery.js"></script>
    <script>
        function findData(){
            $.get("/findData",{},function(data){
               if(data=="数据库打开异常"||data=="建表失败"||data=="查询失败"){
                   alert("查询失败,请重新操作");
               }else{
                   $("#box").html("");//进入查询条件之前清空box中的内容
                   $.each(data,function(i){
                       $("#cx #box").prepend("<dl><dt>姓名</dt><dd>"+data[i].name+"</dd><dt>年龄</dt><dd>"+data[i].age+"</dd></dd>");
                   });
               }
            });
        }
    </script>
    <style>
        #but{margin: auto; width:90px; height:35px; display: block;margin-top:50px;}
        #cx dl{border-bottom: 1px dotted silver; height:30px; width:800px; margin:auto; }
        #cx dl dt{float: left; font-weight: bold; width:150px;}
        #cx dl dd{float: left; color: gray; padding-right:20px; width:150px;}

    </style>
</head>
<body>
    <div id="cx">
        <button id="but" onclick="findData()">查询</button>
        <div id="box">
        </div>
    </div>
</body>
</html>


后台配置路由代码:

var express = require('express');
var router = express.Router();
/* GET home page. */

var mongodb = require("mongodb");
var server = mongodb.Server("127.0.0.1",27017);
var db = new mongodb.Db("add",server);

router.get("/findData",function(req,res){
    db.open(function(err,db){
        if(err){
            res.send("数据库打开异常");
        }else{
            db.collection("users",function(err,collection){
                if(err){
                    res.send("建表失败");
                }else{
                    collection.find().toArray(function(err,doc){ 
           //将查询到的数据以json格式(JavaScript格式)显示
                        if(err){
                            res.send("查询失败");
                        }else{
                            res.send(doc);
                        }
                    });
                }
            });
        }
    })
})
module.exports = router;

点击查询按钮时,效果如图


猜你喜欢

转载自blog.csdn.net/qq_39111062/article/details/80518855