在客戶端的多頁網站中使用 REST API 的最佳方法或最佳實踐是什么?
假設我定義了以下 REST API
/product -> all products, high level information
/product/{id} -> detailed product information about product with given id
進一步假設我的網站有兩個 .html 頁面,index.html以及detail.html.
在內部,index.html我將使用 Javascript 中的 AJAX 呼叫從我的 REST API 查詢具有高級資訊的所有產品。然后,我使用接收到的 JSON 更改 index.html 頁面中的表格元素,并在該表格中顯示每個產品的高級資訊。
每個表條目還具有指向詳細產品資訊的鏈接,例如url/products/42。
現在到了有趣的部分。如果我按下一個特定產品的鏈接,并想顯示detail.html有關所按下產品 id 的詳細資訊的頁面,我如何告訴 detail.html 中的 Javascript 用戶按下了哪個產品并將從 REST API 查詢?
我知道如何在原生移動應用程式中執行這些 REST API 呼叫,因為我總是知道用戶按下了哪個元素。我對如何在多頁網站應用程式上執行此操作有點迷茫。
感謝豐富我的思想:)
uj5u.com熱心網友回復:
有很多方法可以實作你想要的。這里有一些帶有基本代碼示例的線索,以向您展示邏輯。
url/detail.html?product=42當詳細資訊頁面使用類似的東西從 url 加載提取引數時,您可以生成鏈接
// detail.html
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function() {
const queryString = window.location.search;
console.log(queryString);
//?product=42
const urlParams = new URLSearchParams(queryString);
const product = urlParams.get('product')
console.log(product);
// 42
// here request your api with your product
});
您也可以在鏈接上使用點擊事件
<!--index.html-->
<div id="container">
<!-- some html -->
<a href="javascript:void(0)" onclick="loadProduct(42)">
</div>
<script type="text/javascript" src="yourJS.js"></script>
//yourJS.js
let loadProduct = (product) => {
// request API then for example use your detail.html as template to parse response
// and inject into html
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/371903.html
標籤:javascript html 休息 网络
