本文实例讲述了php+jQuery ajax实现的实时刷新显示数据功能。分享给大家供大家参考,具体如下:
创建数据表:demo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
--
-- 表的结构 `demo`
--
CREATE TABLE IF NOT EXISTS `demo` (
`id` int (11) NOT NULL AUTO_INCREMENT,
` name ` varchar (20) COLLATE utf8_bin NOT NULL ,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE =utf8_bin AUTO_INCREMENT=5 ;
--
-- 转存表中的数据 `demo`
--
INSERT INTO `demo` (`id`, ` name `) VALUES
(1, '雷军' ),
(2, '马化腾' ),
(3, '李彦宏' ),
(4, '马云' );
|
服务器文件:demo.php
1
2
3
4
5
6
7
8
|
<?php
$mysqli = new mysqli( "localhost" , "root" , "" , "test" );
$mysqli ->set_charset( 'utf8' );
$query = 'SELECT * FROM demo' ;
$result = $mysqli ->query( $query );
$arr = $result ->fetch_all(MYSQLI_ASSOC);
$info = json_encode( $arr );
echo $json = '{"success":true,"info":' . $info . '}' ;
|
显示数据网页: fresh.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
<html>
<head>
<meta charset= 'utf-8' >
<title>hello</title>
</head>
<body>
<script src= "http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js" ></script>
<script>
function check(){
$.ajax({
type: "GET" ,
url: "./demo.php" ,
dataType: "json" ,
success: function (data){
if (data.success){
var count = data.info.length;
for (i=0;i<count;i++){
var dom = "<tr align='center' id='" +data.info[i].id+ "'><td>" +data.info[i].id+ "</td><td>" +data.info[i].name+ "</td></tr>" ;
var tag = '#' +data.info[i].id;
if (!$(tag).length){
$( "#info" ).append(dom);
}
}
} else {
alert( 'error' );
}
},
error: function (res){
alert(res.status);
}
});
}
window.setInterval(check, 1000); //每秒执行一次
</script>
<body>
<div style= 'width:600px;margin:0 auto;' >
<table border= '1' width= "600px" >
<thead>
<tr><th>id</th><th>name</th></tr>
</thead>
<tbody id= 'info' >
<tr align= 'center' id= '111' ><td>111</td><td>测试</td></tr>
</tbody>
</table>
</div>
</body>
</html>
|
希望本文所述对大家PHP程序设计有所帮助。
原文链接:https://blog.csdn.net/koastal/article/details/50833798