我希望将HTML表单连接到Cosmos文档,而不要具有静态数据。谁能指导我正确的方向?这就是我要处理的静态数据,我已经设置了一个用于测试的本地数据库。感谢您的协助。
var select = document.getElementById("ClosurePlanList"),
arr = ["test1","test2","test3"];
for(var i = 0; i < arr.length; i++)
{
var option = document.createElement("OPTION"),
txt = document.createTextNode(arr[i]);
option.appendChild(txt);
option.setAttribute("value",arr[i]);
select.insertBefore(option,select.lastChild);
}
https://docs.microsoft.com/en-us/azure/cosmos-db/sql-api-nodejs-application#_Toc395783181
答案 0 :(得分:1)
请执行以下步骤:
第1步:在本地托管一个nodejs后端以为您查询CosmosDB,请尝试以下代码:
var express = require('express');
const { CosmosClient } = require("@azure/cosmos");
var app = express();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
next();
});
const endpoint = "<your cosmos db endpoint>"
const key = "<your cosmos db key>"
const dbId = "<DB ID/name>"
const containerId = "<container ID/name>"
app.get('/getData', function (req, res) {
getData().then(
(FeedResponse)=>{
res.end(JSON.stringify(FeedResponse.resources));
},
(err)=>{
console.log(err);
res.end("err");
});
})
function getData(){
const client = new CosmosClient({
endpoint,
key
});
const container = client.database(dbId).container(containerId);
const options = {
maxItemCount: 10000,
maxDegreeOfParallelism: 1000,
bufferItems: true
};
const query = "select c.id,c.name from c";
return container.items.query(query, options).fetchAll();
}
var server = app.listen(8888, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
运行它之后,您可以从http://localhost:8888/getData
获取cosmos db数据。
来自nodejs后端的结果:
这是我使用上述代码中的查询从cosmos db中获得的数据:
第2步:尝试使用以下HTML代码来实现cosmosdb中select标签的选项值:
<html>
<body>
<div>
Plan: <select id = "ClosurePlanList">
</div>
</body>
<script>
let xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:8888/getData');
var select = document.getElementById("ClosurePlanList");
xhr.send();
xhr.onload = function() {
if (xhr.status != 200) { // analyze HTTP status of the response
alert(`Error ${xhr.status}: ${xhr.statusText}`); // e.g. 404: Not Found
} else { // show the result
arr = JSON.parse(xhr.response);
for(var i = 0; i < arr.length; i++)
{
var option = document.createElement("OPTION");
txt = document.createTextNode(arr[i].name);
option.appendChild(txt);
option.setAttribute("value",arr[i].id);
select.insertBefore(option,select.lastChild);
}
}
};
</script>
</html>
不建议直接使用js代码从静态html页面直接从cosmosdb获取数据,因为这样可能会泄漏cosmosdb凭据。
希望有帮助!