1,先定义一个ajax函数,供后面调用
1 function ajax(method,url,data,callback){
2
3 var xhr = null;
4
5 if( window.ActiveXObject ){
6 xhr = new ActiveXObject('Microsoft.XMLHTTP');
7 }else{
8 xhr = new XMLHttpRequest();
9 }
10
11 xhr.onreadystatechange = function(){
12
13 if( xhr.readyState == 4 ){
14
15 if( xhr.status == 200 ){
16
17 callback && callback( xhr.responseText );
18
19 }
20
21 }
22
23 };
24
25 if( method == 'post'){
26
27 xhr.open(method,url);
28 xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
29 xhr.send( encodeURI(data) );
30
31 }else{
32
33 xhr.open(method,url+'?'+encodeURI(data));
34 xhr.send(null);
35
36 }
37
38 }
39 2,要写的html文件,通过ajax从php文件获取data数据
40
41 <!DOCTYPE html>
42 <html lang="en">
43 <head>
44 <meta charset="UTF-8">
45 <title>Document</title>
46 <style type="text/css">
47 img{
48 width: 100px;
49 }
50 </style>
51 </head>
52 <body>
53 <table id="tb">
54 <tr>
55 <th>得分</th>
56 <th>昵称</th>
57 <th>地区</th>
58 <th>openid</th>
59 </tr>
60
61 </table>
62 </body>
63 <script type="text/javascript" src="ajax.js"></script>
64 <script type="text/javascript">
65 var aTb = document.getElementById('tb');
66 ajax(
67 'get',
68 'ranking.php',
69 '',
70 function( data ){
71 console.log( data );
72 data = JSON.parse(data);
73 for (var i in data) {
74 var atr = document.createElement("tr")
75 atr.innerHTML = "<td>"+data[i].score+"</td><td><td><img src="+data[i].headimgurl+"><span>"+data[i].nickname+"</span></td></td><td>"+data[i].country+data[i].province+data[i].city+"</td><td>"+data[i].openid+"</td>";
76 aTb.appendChild(atr);
77
78 };
79
80 }
81 );
82
86 </script>
87 </html>
88
3,php文件:
89 <?php
90 $mysqli=new mysqli(SAE_MYSQL_HOST_M.":".SAE_MYSQL_PORT,SAE_MYSQL_USER,SAE_MYSQL_PASS,SAE_MYSQL_DB);
91 if($mysqli->connect_errno){
92 die($mysqli->connect_error);
93 }
94 $mysqli->query("set names utf-8");
95
96 $sql = "SELECT * FROM `gameRanking`";
97
98 $results = $mysqli->query($sql);
99
100 $arr = array();
101
102 while( $row = $results->fetch_assoc() ){
103
104 //循环取出所有数据并把数据存入数组中。
105
106 array_push( $arr , $row);
107 //array_push(存入到哪个数组中,要存入数组的值)
108 };
109 //将保存所有数据的数组转换成 json字符串
110 $str = json_encode( $arr );
111
112 //将字符串数据返回给前端页面
113 echo $str;
114
115 //关闭数据库连接
116 $mysqli->close();
117
118 ?>