簡體   English   中英

如何將 append html 格式化數據從節點 js 服務器傳輸到客戶端的 html 文件?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM