我是初学程序员。我想知道如何使用按钮提交由JQuery日期选择器和单选按钮组成的表单。我想将表单提交给名为test
的Mongo数据库。在我的home.html
文件中,我调用了我需要的不同样式表和javascript文件。然后我在home.html
中设置了一个输入字段,并在表单下方设置了一个按钮以提交:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Home</title>
<!-- Local CSS and JS -->
<script src="/javascripts/home.js"></script>
<!-- Materialize: Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.0/css/materialize.min.css">
<!-- Materialize: Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.0/js/materialize.min.js"></script>
</head>
<body>
<!-- Input field I want to submit -->
<form method="post" action="/submit">
<input id="test1" type="radio"><label for="test1">Test</label>
<input id="test2" type="radio"><label for="test2">Test 2</label>
<input id="test3" type="radio"><label for="test3">Test 3</label>
</form>
<!-- Button I want to use to submit -->
<button type="submit" class="btn waves-effect waves-light" name="action">Sumbit</button>
</div>
</body>
</html>
现在,我通过输入localhost:3000 / home.html来加载此文件。我想使用我的index.js
文件来编写post方法,以便将数据提交到名为test
的数据库。在做了一些研究后,我发现我需要一些东西来启动index.js
,如:
var express = require('express');
var router = express.Router();
//TALKING TO THE DB?
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert')
var ObjectId = require('mongodb').ObjectID;
var url = 'mongodb://localhost:27017/test';
var bodyParser = require('body-parser');
/*something would follow like?:
router.get('/submit', function(req, res) {
var db = req.test;
});*/
作为参考,我使用快速骨架,所以我的app.js
看起来像:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
// Database
var mongo = require('mongodb');
var monk = require('monk');
//DB TEST
var db = monk('localhost:27017/test');
var routes = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
但是,我很困惑如何设置从我的输入字段中获取数据的路径(使用提交按钮)。然后我想使用post方法将该信息写入我的test
数据库。任何帮助将不胜感激!谢谢!
答案 0 :(得分:2)
在开始学习Node,MongoDB和REST调用时,我发现这两个教程非常有用。
以下是第二篇教程中的一些相关代码
客户机侧:
// Add User button click
$('#btnAddUser').on('click', addUser);
function addUser(event) {
event.preventDefault();
// Super basic validation - increase errorCount variable if any fields are blank
var errorCount = 0;
$('#addUser input').each(function(index, val) {
if($(this).val() === '') { errorCount++; }
});
// Check and make sure errorCount's still at zero
if(errorCount === 0) {
// If it is, compile all user info into one object
var newUser = {
'username': $('#addUser fieldset input#inputUserName').val(),
'email': $('#addUser fieldset input#inputUserEmail').val(),
'fullname': $('#addUser fieldset input#inputUserFullname').val(),
'age': $('#addUser fieldset input#inputUserAge').val(),
'location': $('#addUser fieldset input#inputUserLocation').val(),
'gender': $('#addUser fieldset input#inputUserGender').val()
}
// Use AJAX to post the object to our adduser service
$.ajax({
type: 'POST',
data: newUser,
url: '/users/adduser',
dataType: 'JSON'
}).done(function( response ) {
// Check for successful (blank) response
if (response.msg === '') {
// Clear the form inputs
$('#addUser fieldset input').val('');
// Update the table
populateTable();
}
else {
// If something goes wrong, alert the error message that our service returned
alert('Error: ' + response.msg);
}
});
}
else {
// If errorCount is more than 0, error out
alert('Please fill in all fields');
return false;
}
};
了Serverside:
users.js
/*
* POST to adduser.
*/
router.post('/adduser', function(req, res) {
var db = req.db;
var collection = db.get('userlist');
collection.insert(req.body, function(err, result){
res.send(
(err === null) ? { msg: '' } : { msg: err }
);
});
});
app.js
// Make our db accessible to our router
app.use(function(req,res,next){
req.db = db;
next();
});
app.use('/users', users);
答案 1 :(得分:0)
您的问题是一系列可以通过多种方式解决的小问题或步骤(每一步都取决于工具和代码结构)。因此,最基本的方法是在app.js中打开数据库连接,并使用Express路由器在单独的文件或同一app.js中定义POST路由。
代码:
var router = express.Router();
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server;
var mongoclient = new MongoClient(new Server("localhost", 27017));
var db = mongoclient.db('mydb');
router.post('/myroute', function(req, res){
//Retrieve data sent by the client in the post request
var param1 = req.body.param1;
// Insert document in collection
db.collection('mycollection').insert({ myfield: param1}, function(err, doc) {
if(err) throw err;
//Doc saved
});
});
我建议你通过互联网查看Node.js + MongoDB CRUD教程。 Mongoose是一个可以帮助您定义模式和处理数据库的库。