我有一个基本的HTML表单,它通过JQuery $ AJAX POST向节点发送三个数据字段。当它到达服务器时,存储在 var mov = new Movie(inputDataJSON);
然后完美地存储在Mongo DB中。
然后我想要获取此信息并将其显示在页面上。我一直在尝试使用AJAX POST的成功方法,而不是在任何地方。我已经用MYSQL / PHP做了这样的事情并且已经有了它的工作但是有了node / mongo我有点死路一条。我把那个区域留空了,只是留下了评论。
客户资料
$(function(){
$('#select_link').click(function(e){
e.preventDefault();
// These are all
var movieTitle = $("#movie-title").val();
var movieRating = $("#rating").val();
var movieYear = $("#year").val();
console.log(movieTitle)
var data = {};
data.title = movieTitle;
data.rating = movieRating;
data.releaseYear = movieYear ;
data.hasCreditCookie = true;
$.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
url: '/sendJSON',
success: function(data) {
console.log('success'); // Not sure how to get it back out to display to the page from MongoDB
}
});
});
});
服务器资料
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
var port = 8080;
app.listen(port);
console.log('listening on port: ' + port);
var mongoose = require('mongoose');
var db = mongoose.connection;
db.on('error', console.error);
var inputDataJSON;
db.once('open', function() {
var movieSchema = new mongoose.Schema({
title: {type: String},
rating: String,
releaseYear: Number,
hasCreditCookie: Boolean
});
var Movie = mongoose.model('Movie', movieSchema);
app.use(express.bodyParser());
app.post('/sendJSON', function(req, res) {
inputDataJSONString = JSON.stringify(req.body);
inputDataJSON = JSON.parse(inputDataJSONString);
var mov = new Movie(inputDataJSON);
mov.save(function(err, mov) {
if (err) return console.error(err);
console.dir(mov);
});
});
});
mongoose.connect('mongodb://localhost/test');
并... HTML
<body>
<div id="select_div">
<a href="#" id="select_link">Send Movie</a>
</div>
<div class="container">
<form>
<label>Movie Title</label> <input id="movie-title" type="text" name="title"><br>
<label>Rating</label> <input id="rating" type="text" name="rating"><br>
<label>Year</label> <input id="year" type="text" name="year"><br>
</form>
</div>
</body>