如何在多页面网站上正确使用 REST API

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.htmldetail.html

index.html 中,我会使用 Javascript 中的 AJAX 调用从我的 REST API 查询所有具有高级信息的产品。然后,我用收到的 JSON 更改 index.html 页面内的 table 元素,并在该 table.

内显示每个产品的高级信息

每个 table 条目还有一个 link 到详细的产品信息,例如url/products/42.

现在进入有趣的部分。如果我按下一个特定产品的 link 并想要显示包含有关所按下产品 ID 的详细信息的 detail.html 页面,我如何告诉 detail.html 里面的 Javascript 哪个用户按下并从 REST 查询的产品 API?

我知道如何在本机移动应用程序中执行这些 REST API 调用,因为我总是知道用户按下了哪个元素。我有点不知道如何在多页网站应用程序上执行此操作。

感谢丰富了我的思想:)

有很多方法可以实现您想要的。这里有一些带有基本代码示例的线索可以向您展示逻辑。

您可以生成 link,例如 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
});

您还可以在 link

上使用点击事件
<!--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
};