![](/img/trans.png)
[英]Get data from the client side (html) and sent it back to the server site (Server.js) Node.Js
[英]How to append html formatted data from node js server to html file in client side?
我正在尝试用普通的 javascript、节点和把手构建一个站点,通过报价计算器,用户可以向站点所有者请求几个项目的列表。 json 格式的数据如:
{ "item": "candy", "brand":"delicious candy" }
将由用户在 index.html 中插入。 然后,该站点将执行一些验证,然后通过 fetch api 将其发送到服务器,该按钮以某种方式附加到按钮中的事件,例如“发送报价”
app.post('/api', (request, response) => {
let quote = request.body;
response.render('admin', quote);
然后 HandleBars 会在 html 中插入数据,例如:
<h1> Candy </h1>
<h2> Delicious candy </h2>
这就是我卡住的地方,我能够在控制台中可视化 api 调用的响应,并且显然正在将我想要的数据发送回浏览器,但我无法思考我怎么能 append 这个HTML 到名为 admin.html 的 HTML 文件。
您是否熟悉 jQuery? 您可以在 Handlebars HTML 中创建一个空段落标签。
<p id="candyData">
</p>
然后,在您为表单上的提交按钮添加事件侦听器的 JS 文件中,按 ID 查询段落。
const candyData = document.querySelector('#candyData');
现在,在您获取到服务器的过程中,它可能看起来像这样来获取页面的值。
fetch('/url').then((response) => {
response.json().then((data) => {
if (data.error) {
candyData.textContent = data.error;
} else {
candyData.textContent = data.candyDataObj // candyDataObj should be accessed based on how you're storing the data.
}
});
});
不要忘记在 HTML 文件中加载脚本标签。
<script src="/scripts/app.js"></script> <!-- the src path should be updated per your directory -->
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.