Code demo
<!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>
Code template-web.js
file that we can npm install art-template
install on art-template to get this file, or go to the official website to download https://github.com/aui/art-template
Code I opened a json-server
local service For an introduction to json-server can view this article basic use of json-server
The data used in the code is as follows
{
"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" : "画家"
}
]
}