你好!在这篇文章中我想谈谈如何使用 hmpl.js 从 api 获取 html 并在 dom 中显示。
此方法适用于任何 api,因为此模块基于 fetch api,几乎完全复制了 vanilla 解决方案的工作。
假设我们采用返回 html 响应的路由:
api 路由 – http://localhost:8000/api/test
1
<span>123</span>
并且,比方说,在 id 为“wrapper”的 div 中有一个任务来显示此 html。为此,您可以通过 script 标签连接 hmpl 模块并编写以下代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<div i源码网点我wcqh.cnd=”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”
}
}
`
);
const wrapper = document.getelementbyid(“wrapper”);
const obj = templatefn();
wrapper.appendchild(obj.response);
</script>
在源码网点我wcqh.cn这段代码中,借助 hmpl 标记,您可以生成可以在 html 中显示的 dom 节点。值得考虑的是,该节点将在 api 请求过程中自动更新。
立即学习“前端免费学习笔记(深入)”;
如果需要添加请求指示器,可以稍微扩展现有代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<div id=”wrapper”></div>
<script src=”https://unpkg.com/hmpl-js/dist/hmpl.min.js”></script><script>
const templateFn = hmpl.compile(
`<div>
{
{
“src”:”http://l源码网点我wcqh.cnocalhost:8000/api/test”,
“on”: {
“trigger”: “loading”,
“content”: “<div>Loading…”,
}
}
}
`
);
const wrapper = document.getElementById(“wrapper”);
const obj = templateFn();
wrapper.appendChild(obj.response);
</script>
在本例中,当请求发送后,但 api 的响应尚未到达时,该指标就会被触发。
以上就是如何使用 HMPLjs (fetch) 从 API 获取 HTML 并在 DOM 中显示?的详细内源码网点我wcqh.cn容,更多请关注青狐资源网其它相关文章!
暂无评论内容