首頁  >  文章  >  web前端  >  如何使用 HMPL.js (fetch) 從 API 取得 HTML 並在 DOM 中顯示?

如何使用 HMPL.js (fetch) 從 API 取得 HTML 並在 DOM 中顯示?

王林
王林原創
2024-07-22 21:14:03502瀏覽

How to GET HTML from API and Display In DOM using HMPL.js (fetch)?

您好!在這篇文章中我想談談如何從 API 取得 HTML 並使用 HMPL.js 在 DOM 中顯示。

此方法適用於任何 api,因為此模組基於 Fetch API,幾乎完全複製了普通解決方案的工作。

假設我們採用傳回 HTML 回應的路由:

API 路由 - http://localhost:8000/api/test

<span>123</span>

並且,假設在 id 為「wrapper」的 div 中有一個任務來顯示此 HTML。為此,您可以透過 script 標籤連接 hmpl 模組並編寫以下程式碼:

<div id="wrapper"></div>
<script src="https://unpkg.com/hmpl-js/dist/hmpl.min.js"></script>
<script>
  const templateFn = hmpl.compile(
    `<div>
       { 
         {
           "src":"http://localhost:8000/api/test" 
         } 
       }
    </div>`
  );

  const wrapper = document.getElementById("wrapper");

  const obj = templateFn();

  wrapper.appendChild(obj.response);
</script>

在這段程式碼中,借助 hmpl 標記,您可以產生可以在 HTML 中顯示的 DOM 節點。值得考慮的是,該節點將在 API 請求過程中自動更新。

如果需要加入請求指示器,可以稍微擴充現有程式碼:

<div id="wrapper"></div>
<script src="https://unpkg.com/hmpl-js/dist/hmpl.min.js"></script>
<script>
  const templateFn = hmpl.compile(
    `<div>
       { 
         {
           "src":"http://localhost:8000/api/test",
           "on": {
              "trigger": "loading",
              "content": "<div>Loading...</div>",
           } 
         } 
       }
    </div>`
  );

  const wrapper = document.getElementById("wrapper");

  const obj = templateFn();

  wrapper.appendChild(obj.response);
</script>

在本例中,當請求發送,但 API 的回應尚未到達時,該指標將被觸發。

以上是如何使用 HMPL.js (fetch) 從 API 取得 HTML 並在 DOM 中顯示?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn