【发布时间】:2018-09-10 23:18:49
【问题描述】:
我是 Node/JS/Ajax 和所有这些东西的新手。 我有一个发送数组响应的应用程序。我想在我的 html 中从该数组中填充一个选择。这是我目前所拥有的:
app.js
app.get('/', function(req, res) {
res.sendFile('/public/html/index.html');
});
app.get('/collectionnames', function(req, res) {
var collectionnames = [];
MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true }, function (err, client) {
if (err) {
console.log("Error");
} else {
console.log("Connected to MongoDB to get collections...");
}
var db = client.db('mydb');
db.listCollections().toArray(function (err,collections) {
collections.forEach(function(collection){
var elem = new Object();
if (collection.name !== "system.indexes"){
//console.log(collection.name);
elem = collection.name;
collectionnames.push(elem);
};
});
console.log("got collections...")
console.log(collectionnames);
res.send(collectionnames);
});
});
});
我的 index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/css/style.css">
</head<
<body onload="getCollections()">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="javascript/test.js"></script>
</body>
</html>
我的 test.js
function getCollections() {
$.ajax({
type: "GET",
url: '/collectionnames',
})
// .done(function(data) {
// alert(data.join(' '));
// })
}
只要我使用 test.js 接收数组/值并且可以使用“alert(data.join(' '));”看到它,这就是有效的我现在想要的是在我的 index.html 中有一个选择表单,它由数组(数据)中的/作为选项提供,但我不知道如何。
我可以请人帮忙吗?
【问题讨论】:
-
所有 AJAX 和 node.js 的东西都是完全无关的。您只需向我们展示
console.log(data)的输出。构造一个选项元素很简单:$('<option>').val(1).text('blah') -
用 jQuery 创建元素:api.jquery.com/jQuery/#jQuery2
标签: javascript jquery node.js ajax