[英]How to consume a REST API properly on a multi page website
在客戶端的多頁網站中使用 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
。
Inside the index.html
I would query all products with high level information from my REST API with an AJAX call in Javascript. 然后,我使用收到的 JSON 更改 index.html 頁面內的表格元素,並在此表格中顯示每個產品的高級信息。
每個表條目還具有指向詳細產品信息的鏈接,例如url/products/42
。
現在到有趣的部分。 If I press the link of one specific product and want to show the detail.html
page with detailed information about the pressed product id, how to I tell the Javascript inside detail.html which product the user pressed and is to be queried from the REST API?
我知道我是如何在原生移動應用程序中執行這些 REST API 調用的,因為我一直都知道用戶按下了哪個元素。 我有點迷失如何在多頁網站應用程序上執行此操作。
感謝豐富我的思想:)
有很多方法可以實現您想要的。 這里有一些帶有基本代碼示例的線索來向您展示邏輯。
您可以生成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
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.