Javascript Node/Express的MongoDB示例的AJAX调用?
这是从一个非常基本的页面开始的:HTML表单、按钮和div框 。单击按钮将通过AJAX发布表单数据 数据将存储在MongoDB中,并在不刷新页面的情况下检索到div框中 index.html中的AJAX: app.js: JSON如何/从哪里连接到MongoDB? 此外,Express是否需要一个模板引擎,例如Consolidate?如果是这样的话,那该如何/在哪里适应呢?没有什么建议 关于index.html中的ajax调用Javascript Node/Express的MongoDB示例的AJAX调用?,javascript,jquery,ajax,node.js,mongodb,Javascript,Jquery,Ajax,Node.js,Mongodb,这是从一个非常基本的页面开始的:HTML表单、按钮和div框 。单击按钮将通过AJAX发布表单数据 数据将存储在MongoDB中,并在不刷新页面的情况下检索到div框中 index.html中的AJAX: app.js: JSON如何/从哪里连接到MongoDB? 此外,Express是否需要一个模板引擎,例如Consolidate?如果是这样的话,那该如何/在哪里适应呢?没有什么建议 关于index.html中的ajax调用 如果您的index.html由同一台服务器提供,请不要使用跨域调用。
index.html
由同一台服务器提供,请不要使用跨域调用。$中的url
属性。ajax
可以是类似于/start
的相对url李>
jsonp
request$.ajax({
dataType: 'json',
data: $('#formID').serialize(),
type: 'POST',
url: "./start",
success: handleButtonResponse,
});
JSON如何/从哪里连接到MongoDB?
在ajax调用中,您请求的是/start
,因此应该在express服务器中执行相同的路由。像
app.get('/start', function (req, res) {
db.collection('collectionName').insert({req.data}, function (err, doc) {
//rest of code
});
});
Express是否需要模板引擎,如Consolidate?如果是,如何/在何处适用?
您有很多模板选择,比如jade、ejs、hbs等等。
如果您使用jade或其中任何一种,那么express routes中的html呈现代码将得到简化
没有模板引擎
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();
使用像jade这样的模板引擎(现在是帕格)
此外,使用模板引擎,您可以使用服务器端变量呈现模板,并可以在模板中访问它们,如
app.get('/mypage', function (req, res) {
res.render('mytemplate_page',{template_variable:some_variable});
});
您还可以在模板内使用
template\u变量
进行循环或显示。感谢您提供了非常有用的答案。(submittedPost)与{req.data}的关系如何?这只是为了演示服务器端的ajax路由。希望有帮助。
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();
var submittedPost = {};
submittedPost['message'] = 'Proof that Node and Mongo are working..';
response.json(submittedPost);
app.get('/mypage', function (req, res) {
res.render('mytemplate_page',{template_variable:some_variable});
});