最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AJAX call tofrom MongoDB example for NodeExpress? - Stack Overflow

programmeradmin7浏览0评论

This is to start with a very basic page: HTML Form, a button, and a div-box.

.click of the button would POST the Form data through AJAX.

The data is to be stored in MongoDB, and retrieved into the div-box without a page-refresh.

AJAX from index.html:

$(document).ready(function()
{   

    // handle button clicks         
    $('#buttonID').click(function() {

        // make an ajax call
        $.ajax({
            dataType: 'jsonp',
            jsonpCallback: '_wrapper',
            data: $('#formID').serialize(),
            type: 'POST',
            url: "http://localhost:9999/start",
            success: handleButtonResponse,
            });
    });

    function handleButtonResponse(data)
    {
        // parse the json string
        var jsonObject = JSON.parse(data);
        $('#reponseID').append( jsonObject.message );
    }

});

app.js:

var express = require('express'),
    app = express();
    cons = require('consolidate');
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server;

app.engine('html', cons.swig);
app.set('view engine', 'html');
app.set('views', __dirname + "/views");

var mongoclient = new MongoClient(new Server('localhost', 27017,
                                                { 'native_parser' : true }));

var db = mongoclient.db('database_name');

app.get('/', function (req, res) {

    db.collection('collectionName').find({}, function (err, doc) {
            res.render('index', doc);   
    });

    response.writeHead(200, {"Content-Type:": "application/json"}); 
    var submittedPost = {};
    submittedPost['message'] = 'Proof that Node and Mongo are working..';
    response.write( "_wrapper('" );
    response.write( JSON.stringify(submittedPost) );
    response.write( "')");              
    response.end();

});

app.get('*', function (req, res) {
    res.send("404..", 404);
});

mongoclient.open(function (err, mongoclient) {

    if (err) throw err

    app.listen(9999);
    console.log("Express server started on port 9999");
});

How/Where does the JSON connect to/from MongoDB?

Also, does Express require a templating engine, such as Consolidate? If so, how/where does that fit in?

This is to start with a very basic page: HTML Form, a button, and a div-box.

.click of the button would POST the Form data through AJAX.

The data is to be stored in MongoDB, and retrieved into the div-box without a page-refresh.

AJAX from index.html:

$(document).ready(function()
{   

    // handle button clicks         
    $('#buttonID').click(function() {

        // make an ajax call
        $.ajax({
            dataType: 'jsonp',
            jsonpCallback: '_wrapper',
            data: $('#formID').serialize(),
            type: 'POST',
            url: "http://localhost:9999/start",
            success: handleButtonResponse,
            });
    });

    function handleButtonResponse(data)
    {
        // parse the json string
        var jsonObject = JSON.parse(data);
        $('#reponseID').append( jsonObject.message );
    }

});

app.js:

var express = require('express'),
    app = express();
    cons = require('consolidate');
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server;

app.engine('html', cons.swig);
app.set('view engine', 'html');
app.set('views', __dirname + "/views");

var mongoclient = new MongoClient(new Server('localhost', 27017,
                                                { 'native_parser' : true }));

var db = mongoclient.db('database_name');

app.get('/', function (req, res) {

    db.collection('collectionName').find({}, function (err, doc) {
            res.render('index', doc);   
    });

    response.writeHead(200, {"Content-Type:": "application/json"}); 
    var submittedPost = {};
    submittedPost['message'] = 'Proof that Node and Mongo are working..';
    response.write( "_wrapper('" );
    response.write( JSON.stringify(submittedPost) );
    response.write( "')");              
    response.end();

});

app.get('*', function (req, res) {
    res.send("404..", 404);
});

mongoclient.open(function (err, mongoclient) {

    if (err) throw err

    app.listen(9999);
    console.log("Express server started on port 9999");
});

How/Where does the JSON connect to/from MongoDB?

Also, does Express require a templating engine, such as Consolidate? If so, how/where does that fit in?

Share Improve this question asked Dec 2, 2013 at 5:11 user3056035user3056035 431 gold badge1 silver badge3 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 4

Few suggestions

Regarding the ajax call in index.html

  1. If your index.html is served by the same server, then please don't use a cross domain call. The url property in $.ajax could be a relative url like /start.
  2. Also you can think of not using jsonp request.

the call could be like

$.ajax({
    dataType: 'json',
    data: $('#formID').serialize(),
    type: 'POST',
    url: "./start",
    success: handleButtonResponse,
});

How/Where does the JSON connect to/from MongoDB?

In you ajax call you are requesting for ./start, So the same route should be made in your express server. like

app.get('/start', function (req, res) {    
    db.collection('collectionName').insert({req.data}, function (err, doc) {
           //rest of code 
    });    
});

does Express require a templating engine, such as Consolidate? If so, how/where does that fit in?

You have many options for templating like jade,ejs,hbs and so on. If you use jade or any of them your html rendering code in express routes will get simplified.

without a templating engine

response.writeHead(200, {"Content-Type:": "application/json"}); 
var submittedPost = {};
submittedPost['message'] = 'Proof that Node and Mongo are working..';
response.write( "_wrapper('" );
response.write( JSON.stringify(submittedPost) );
response.write( "')");              
response.end();

with a templating engine like jade (now pug)

var submittedPost = {};
submittedPost['message'] = 'Proof that Node and Mongo are working..';
response.json(submittedPost);

also with templating engines you can render templates with server side variables and you can access them inside your templates like

app.get('/mypage', function (req, res) { 
    res.render('mytemplate_page',{template_variable:some_variable});
});   

and you can use template_variable inside the template for looping through or displaying.

发布评论

评论列表(0)

  1. 暂无评论