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