代码演示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
<form id="user_form">
</form>
<script type="text/template" id="tpl">
姓名:<input type="text" value="{
{user.username}}">
<br>
年龄:<input type="text" value="{
{user.age}}">
<br>
职业:
<select name="">
{
{
each jobs}}
{
{
if $value.id === user.job}}
<option value="{
{$value.id}}" selected>{
{
$value.name}}</option>
{
{
else}}
<option value="{
{$value.id}}">{
{
$value.name}}</option>
{
{
/if}}
{
{
/each}}
</select>
</script>
<script src="./template-web.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
<script>
$(function () {
$.get('http://localhost:3001/users/3', function (userData) {
$.get('http://localhost:3001/jobs', function (jobsData) {
let result = template('tpl', {
user: userData,
jobs: jobsData
});
document.getElementById("user_form").innerHTML = result;
})
})
});
</script>
</body>
</html>
- 代码中的
template-web.js
文件我们可以通过 npm install art-template
安装上art-template 后拿到这个文件,或者去官网下载 https://github.com/aui/art-template
- 代码中我开启了一个
json-server
本地服务,有关json-server的介绍可以查看这篇文章 json-server的基本使用
- 代码中使用到的数据如下
{
"users": [
{
"id": 1,
"username": "admin1",
"age": 18,
"job": 1
},
{
"id": 2,
"username": "admin2",
"age": 28,
"job": 2
},
{
"id": 3,
"username": "admin3",
"age": 38,
"job": 3
}
],
"jobs": [
{
"id": 1,
"name": "学生"
},
{
"id": 2,
"name": "老师"
},
{
"id": 3,
"name": "司机"
},
{
"id": 4,
"name": "黑客"
},
{
"id": 5,
"name": "画家"
}
]
}