<!-- html模板:1.html -->
序号<id>
<table width=50% border=1 cellspacing=0 cellpadding=2>
<tr><td>姓名</td><td><name></td><td>性别</td><td><sex></td></tr>
<tr><td>年龄</td><td><age></td><td>地址</td><td><addr></td></tr>
</table>
<?php
//php读取html模板并向js传输数据实现JS翻页显示
header('Content-Type:text/html;charset=utf-8');
?>
<html>
<title>测试</title>
<body>
<center>
<font color=red><h1>php读取html模板并向js传输数据实现JS翻页显示</h1></font><hr>
<?php
/*数组数据,下标1开始*/
$arr = array(
1=>array('id'=>'11','name'=>'AA','sex'=>'M', 'age'=>'23', 'addr'=>'66号'),
array('id'=>'22','name'=>'BB','sex'=>'F', 'age'=>'22', 'addr'=>'77号'),
array('id'=>'33','name'=>'CC','sex'=>'M', 'age'=>'24', 'addr'=>'88号')
);
/*html模板*/
$str = file_get_contents('1.html');
/*模板替换值*/
foreach($arr as $rowk => $arr2){
foreach($arr2 as $k=>$v){
if($k=='id') $v=$rowk;
$str = str_replace('<'.$k.'>','<span id=id_'.$k.'>'.$v.'</span>',$str);
}
}
/*显示html页面*/
echo $str;
/*js操作:数组数据先转为json字符串传输,再转置json数据结构*/
$js_str=json_encode($arr);
echo "<script>
var js_arr=JSON.parse('$js_str');
console.table(js_arr);
var arr_length = count(js_arr);
var i=1;
function up_disp(){
i--;
if(i<1) i=1;
//console.table(arr_length,i);
console.log(js_arr[i]['name'],js_arr[i]['sex'],js_arr[i]['age'],js_arr[i]['addr']);
rec_disp(i);
}
function down_disp(){
i++;
if(i>arr_length) i=arr_length;
console.log(js_arr[i]['name'],js_arr[i]['sex'],js_arr[i]['age'],js_arr[i]['addr']);
rec_disp(i);
}
function rec_disp(i){
//chrome
document.querySelector('#id_num').innerText='[共'+arr_length+'条,当前第'+i+'条]';
document.querySelector('#id_id').innerText=i;
document.querySelector('#id_name').innerText=js_arr[i]['name'];
document.querySelector('#id_sex').innerText=js_arr[i]['sex'];
document.querySelector('#id_age').innerText=js_arr[i]['age'];
document.querySelector('#id_addr').innerText=js_arr[i]['addr'];
}
function count(o){
var n = 0;
for(var i in o) n++;
return n;
}
</script>";
echo "<span id=id_num>",'[共',count($arr),'条,当前第',$rowk,'条]',"</span> ";
echo "<input type=button value='上一条' onclick=\"up_disp();\"> ";
echo "<input type=button value='下一条' onclick=\"down_disp();\"> ";
?>
</center>
</html>
|