模板引擎
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>模板引擎</title> <style> td span { color: red; } </style> </head> <body> <button>按钮</button> <table> <thead> <tr> <td>序号</td> <td>姓名</td> <td>年龄</td> <td>性别</td> <td>专辑</td> </tr> </thead> <tbody> </tbody> </table> <script type="text/template" id="tpl"> {{each lists}} <tr> <td>{{$index+1}}</td> <td>{{$value.name}}</td> <td>{{$value.age}}</td> <td>{{$value.gender}}</td> <td>{{$value.ablum}}</td> </tr> {{/each}} </script> <script type="text/template" id="tpl2"> {{each lists as val key}} <tr> <td>{{key+1}}</td> <td>{{val.name}}</td> {{if val.age > 50}} <td><span>{{val.age}}</span></td> {{else}} <td>{{val.age}}</td> {{/if}} <td>{{val.gender}}</td> <td>{{val.ablum}}</td> </tr> {{/each}} </script> <script src="./template-web.js"></script> <script> var btn = document.querySelector('button'); btn.addEventListener('click', function () { var xhr = new XMLHttpRequest; xhr.open('get', './stars.php'); xhr.send(); xhr.addEventListener('readystatechange', function () { if(xhr.readyState == 4 && xhr.status == 200) { var data = JSON.parse(xhr.responseText); console.log(data); var html = template('tpl2', {lists: data}); console.log(html); document.querySelector('tbody').innerHTML = html; } }) }) </script> </body> </html>
start.php 代码
1 <?php 2 3 $stars = array( 4 array('name'=>'刘德华', 'age'=>58, 'gender'=>'男', 'ablum'=>'一起走过的日子'), 5 array('name'=>'王力宏', 'age'=>38, 'gender'=>'男', 'ablum'=>'心跳'), 6 array('name'=>'孙燕姿', 'age'=>42, 'gender'=>'女', 'ablum'=>'绿光'), 7 array('name'=>'吴彦祖', 'age'=>18, 'gender'=>'男', 'ablum'=>'好歌'), 8 array('name'=>'刘备', 'age'=>108, 'gender'=>'男', 'ablum'=>'三顾茅庐') 9 ); 10 11 // 将数组转成了 json 格式的字符串 12 echo json_encode($stars);
♪♫♬
梦想我想不只是拿来实现的,它可以提醒我们,我们可以努力,我们可以变更好。