node.js - 使用ajax从mongoose获取数据到前端
问题描述
由于我是 node.js 和 MongoDB 的新手,所以在尝试在网页中显示值(如 crud)时出现错误。我想在用户提交表单后向前端显示猫鼬值。我在控制台中获取数据,而不是在网页上
请任何人帮忙。谢谢
user_controller.js
const Admin = require('../models/user_model');
exports.adduser = (req, res, next) => {
const name =req.body.name;
const quote = req.body.quote;
const Admin_save= new Admin();
Admin_save.name=name;
Admin_save.quote=quote;
console.log(Admin_save.name);
console.log(Admin_save.quote);
Admin_save.save()
.then(result =>{
//console.log(result);
console.log('Created Admin_panel');
res.redirect('/firstpage')
})
}
user_model 模式
const adminSchema = new Schema({
name :
{
type :String
},
quote :
{
type: String
}
});
我想使用 ajax 和我的 ajax 文件显示
$('submit').click(function() {
$.ajax({
type: 'POST',
url: 'mongodb://localhost:27017/data',
data: $(formid).serialize(),
dataType:"json", //to parse string into JSON object,
success: function(data){
if(data){
var len = data.length;
var txt = "";
if(len > 0){
for(var i=0;i<len;i++){
if(data[i].name && data[i].quote){
txt += "<tr><td>"+data[i].name+"</td><td>"+data[i].quote+"</td></tr>";
}
}
if(txt != ""){
$("#table").append(txt).removeClass("hidden");
}
}
}
},
error: function(jqXHR, textStatus, errorThrown){
alert('error: ' + textStatus + ': ' + errorThrown);
}
});
return false;//suppress natural form submission
});
解决方案
您不能通过 ajax 直接访问 mongodb 数据。
您需要在 nodejs 中创建一个新的 api 来读取数据,然后在该读取的 api 上调用 ajax 请求。
推荐阅读
- c# - 如何在图像上填充旋转的矩形?
- javascript - setState 后无法获取表单数据
- php - 如何在html中插入foreach函数?
- matlab - 拟合分段方程时如何确定范围?
- django - 如何防止在 Django 网站上(大量)共享帐户?
- java - 从一维数组自动生成可变大小的二维数组
- spring-boot - 应用程序开发的骆驼路线
- django - Django Inline:如何在 change_view() django 中获取内联属性
- c++ - 什么是 LibAV 中的`linesize`
- highcharts - 如何在不降低图表高度的情况下减少图例在顶部对齐的类型列的高图表中的图例和图表之间的差距?