我有一个简单的HTML网页表单,其中包含一个选择框。我想设置选项以使用我的MSSQL查询的结果。 (这是产品编号列表)
以下是我目前的情况:
var {TYPES, Request, Connection} = require('tedious');
// Create connection to database
var config = {
userName: 'user',
password: '123123',
server: 'someserver',
options: {
instanceName: 'test'
}
};
var connection = new Connection(config);
// Attempt to connect and execute queries if connection goes through
connection.on('connect', (err) => {
if(err){
console.log(err);
}
run();
});
function run(request, result){
request = new Request("USE Database; SELECT PartNumber FROM dbo.Master ORDER BY PartNumber;", (err) =>{
if(err){
console.log(err);
connection.close();
}
connection.close();
});
var result = "";
request.on('row', (columns) =>{
columns.forEach((column) =>{
result+= column.value + " ";
});
console.log(result);
result = "";
});
connection.execSql(request);
}
<div class="row">
<div class="col span-1-of-3">
<label for="partnumber">PartNumber</label>
</div>
<div class="col span-2-of-3">
<select>
<option required></option>
</select>
</div>
</div>
我在网上找到任何这方面的例子都很麻烦。我想单击选择框,然后出现JavaScript代码中的列表。我可以运行控制台并查看结果,但无法填充选项。
答案 0 :(得分:1)
你可以尝试这样的事情。您需要循环结果并从每个项目创建选项。
var {TYPES, Request, Connection} = require('tedious');
// Create connection to database
var config = {
userName: 'user',
password: '123123',
server: 'someserver',
options: {
instanceName: 'test'
}
};
var connection = new Connection(config);
// Attempt to connect and execute queries if connection goes through
connection.on('connect', (err) => {
if(err){
console.log(err);
}
run();
});
function run(request, result){
request = new Request("USE Database; SELECT PartNumber FROM dbo.Master ORDER BY PartNumber;", (err) =>{
if(err){
console.log(err);
connection.close();
}
connection.close();
});
var result = "";
request.on('row', (columns) =>{
columns.forEach((column) =>{
var opt = document.createElement("option");
opt.value = column.value;
opt.innerHTML = column.value;
document.getElementById('results').appendChild(opt);
result+= column.value + " ";
});
console.log(result);
result = "";
});
connection.execSql(request);
}
<div class="row">
<div class="col span-1-of-3">
<label for="partnumber">PartNumber</label>
</div>
<div class="col span-2-of-3">
<select id="results">
<option required></option>
</select>
</div>
</div>