cquzjh的专栏

天行健,君子当自强不息。地势坤,君子以厚德载物。

原创  AJAX与PHP的结合使用 收藏

 

对AJAX的大名早有耳闻,但真正使用它却是最近才开始的。在近期的工作中需要作一个具有实况转播功能的网站,它和GPS相结合,实时的将用户的最新位置以WEB MAP方式展现出来。一开始我用的是传统的页面定期刷新的方法来实现,但感觉太过于浪费系统的资源,经常会出现页面无响应的现象。而后就想到用实现最流行的AJAX来试一下,看看对性能有否提高。下面是我所使用的代码(其中服务器段用的是PHP代码)

Server.php

<?php 

    
Header("Content-type:text/html;charset=GBK");//加入头,防止乱码
    error_reporting(all);
    
session_start();

    
$deviceid = $_SESSION['deviceid'];
        
    
$onepage = (isset($_REQUEST['recordsonpage'])) ? $_REQUEST['recordsonpage':20;
    
$allpages = 0;
        
    
$link = mysql_connect("10.23.0.202", "gps", "a12345")or die("Could not connect : " . mysql_error());
    
mysql_select_db("gpsdemo") or die("Could not select database");
         
    
$query = sprintf("SELECT * FROM LOGS WHERE `DEV_ID` = '%s' ORDER BY `ReportTime` DESC", $deviceid);
    
    
//first query to get the total records
    $result = mysql_query($query) or die("Query failed : " . mysql_error());

    
$count  = mysql_num_rows($result);
    
$allpages = ceil($count / $onepage);
    
    
$page = $_REQUEST['page'? $_REQUEST['page': 1;
    
    
if($page > $allpages)
        
$page = $allpages;
    
if($page < 1)
        
$page = 1;
    
    
$start = ($page - 1* $onepage;
    
    
//re-construct the sql and query
    $end = (($start + $onepage> $count? $count : ($start + $onepage);
    
$query = sprintf("%s %s %d, %d", $query, "limit", $start, $onepage);
    
$result = mysql_query($query) or die("Query failed : ".mysql_error());
    
$start1 = $start + 1;
    
    
//////////////////////////////////////////////////////////
    //add by Jinghua, for test lingtu encrypt point, 07062006

    $row = mysql_fetch_array($result, MYSQL_BOTH);
    
    
$responseText = NULL;
    
    
//record deviceid, records count,page count and current pageid
    $responseText .= $deviceid . "###" . $count . "###" . $allpages . "###" . $page . "###";
    
     
while($row = mysql_fetch_array($result, MYSQL_BOTH))
    {
        
$cnt++;
        
        
//一条记录用"###"隔开.每列数据用"@@@"隔开. 
        $responseText .= $row[1. "@@@" . $row[2. "@@@";
        
$responseText .= $row[3. "@@@" . $row[4. "@@@";
        
$responseText .= $row[5. "@@@" . $row[6. "@@@" . $row[7];
        
$responseText .= "###";
    }
        
        
echo $responseText;
?>

 

 

 Client.html

 

<script language="JavaScript" src="test.js"></script>

<body>
<div id="RecInfo"></div>
<table width="95%" border="1" align="center" cellpadding="1" cellspacing="0" bordercolor="#000000">
        
<tr bgcolor="#DADADC">
            
<td>                
                
&nbsp;&nbsp;
                
<input type="text" name="timeInterval" id="timeInterval" onFocus="clearValue()" value="time interval" size="15">(s)&nbsp;
                
<input type="button" id="autoRefresh" name="autoRefresh" value="Start Refresh" onClick="refresh()">
                
&nbsp;&nbsp;&nbsp;&nbsp;
                
<select name="recordsperpage" id="recordsperpage" onChange="changeRecPerPage()">
                  
<option value="20">20</option>
                  
<option value="50">50</option>
                  
<option value="100">100</option>
                  
<option value="200">200</option>
                  
<option value="500">500</option>
                  
<option value="1000">1000</option>
                
</select>
                
<font color="red">logs/page</font>
                
&nbsp;&nbsp;&nbsp;&nbsp;        
            </td>
            
<td width="22%" align="right" id="navigationCell">&nbsp;
            
</td>
        
</tr>
        
<tr><td colspan = 2>
            
<table width='95%' border='1' align='center' cellpadding='2' cellspacing='0' bordercolor='#666666' id='myTable'>
                
<thead>
                    
<tr bgcolor="#F2F2F2">
                        
<th>Client Number</th>
                        
<th>Report Time</th>
                        
<th>Longitude</th>
                        
<th>Latitude</th>
                        
<th>Altitude</th>
                        
<th>Speed</th>
                        
<th>Heading</th>
                        
<th>Map</th>
                    
</tr>
                
</thead>
            
</table>
        
</td></tr>
    
</table>
</body>

 

 

test.js

 

var allpage    = 0;
var currentpage = 1;
var recordsonpage = 20;
var recordscnt = 0;
var deviceid = 0;
var refreshflag = 0;

function GetResult()
{
    
/*
    *--------------- GetResult() -----------------
    * GetResult() 
    * 功能:通过XMLHTTP发送请求,返回结果.
    * 参数:str,字符串,发送条件.
    * 实例:GetResult();
    *--------------- GetResult() -----------------
    
*/

    
//开始初始化XMLHttpRequest对象
    http_request = false
    
    
if(window.XMLHttpRequest) //Mozilla 浏览器
        http_request = new XMLHttpRequest();
        
if (http_request.overrideMimeType) {//设置MiME类别
            http_request.overrideMimeType('text/xml');
        }

    }

    
else if (window.ActiveXObject) // IE浏览器
        try {
            http_request 
= new ActiveXObject("Msxml2.XMLHTTP");
        }
 catch (e) {
            
try {
                http_request 
= new ActiveXObject("Microsoft.XMLHTTP");
            }
 catch (e) {}
        }

    }

    
if (!http_request) // 异常,创建对象实例失败
        window.alert("不能创建XMLHttpRequest对象实例.");
        
return false;
    }

    
    
//processRequest is the callback function
    http_request.onreadystatechange = processRequest;
    
    
//需要POST的值,把每个变量都通过&来联接
    var postStr  = "recordsonpage="+ recordsonpage + "&page=" + pageID;
    
    
//var url = "server.php?" + postStr;

    
//特殊字符:+,%,&,=,?等的传输解决办法.字符串先用escape编码的.
    http_request.open("POST","server.php"true);
//    http_request.open("GET", url, true);
    
    
//定义传输的文件HTTP头信息
    http_request.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 
    
                     
//POST method
    http_request.send(postStr);
                     
//Get method
                     http_request.send(null)
}


function processRequest()
{
    
if (http_request.readyState == 4// 判断对象状态
        if (http_request.status == 200// 信息已经成功返回,开始处理信息
            //服务器端处理返回的是经过escape编码的字符串.
            var strResult = unescape(http_request.responseText);
            
//将字符串分开.
            var arrResult = strResult.split("###");
            
            
//取得总页数和当前页面数
            deviceid = arrResult[0];
            recordscnt 
= arrResult[1];
            allpage 
= arrResult[2];
            currentpage 
= arrResult[3];
            
            
//页面导航
            var navigationHTML = null;
            
            
if(parseInt(currentpage, 10> 1)
            
{
                navigationHTML 
= "<input type='button' id='firstpage' name='firstpage' onClick='first()' value='<<'>";
                                            
                navigationHTML 
+= "&nbsp;&nbsp;";
                
                navigationHTML 
+= "<input type='button' id='previouspage' name='previouspage' onClick='previous()' value='<'>";
                    
                navigationHTML 
+= "&nbsp;&nbsp;";
            }


            
if(navigationHTML == null)            
                navigationHTML 
= "<input type='button' id='backtohome' name='backtohome' onClick="window.open('/webtest/main.php', '_parent')" value='HOME'>";
            
else
                navigationHTML 
+= "<input type='button' id='backtohome' name='backtohome' onClick="window.open('/webtest/main.php', '_parent')" value='HOME'>";

            
if(parseInt(allpage, 10> parseInt(currentpage, 10))
            
{
                navigationHTML 
+= "&nbsp;&nbsp;";
                navigationHTML 
+= "<input type='button' id='nextpage' name='nextpage' onClick='next()' value='>'>";
                        
                navigationHTML 
+= "&nbsp;&nbsp;";
                
                navigationHTML 
+= "<input type='button' id='lastpage' name='lastpage' onClick='last()' value='>>'>";
            }

            navigationHTML 
+= "&nbsp;";

            document.getElementById(
"navigationCell").innerHTML = navigationHTML;
            
            RemoveRow(); 
//删除以前的数据.
            
            
var tb = document.getElementById("myTable");
            
            
var data = new Array(2);
            
            
//将取得的字符串分开,并写入表格中.
            for(var i=4;i<arrResult.length - 1;i++)
            
{
                index 
= i - 3;
                row 
= tb.insertRow(index);
                
if(i % 2 == 1)
                
{
                    row.bgColor 
= '#F2F2F2';
                }

            
                arrTmp 
= arrResult[i].split("@@@");
                
                
                
for(var j=0; j<arrTmp.length;j++)
                
{                    
                    num 
= arrTmp[j];
                    cell 
= row.insertCell();
                    cell.align 
= "center";
                    cell.innerText 
= num;                    
                }

                
                
//insert showMAP button for single point
                cell = row.insertCell();
                cell.align 
= "center";
                cell.innerHTML 
= "<input name='showMAP' type='button' onClick= requestSingleMAP("+ arrTmp[2+ ',' + arrTmp[3+ ") value='Show MAP'>";
            }

        }

        
else
        
{//page exception
            alert("The page you request has exception");
        }

    }

    
else
    
{//reading data, not finish
    }

}


function next()
{
    pageID 
= parseInt(currentpage, 10+ 1;
    GetResult();
}


function last()
{
    pageID 
= allpage;
    GetResult();
}


function previous()
{
    pageID 
= parseInt(currentpage) - 1;
    GetResult();
}


function first()
{
    pageID 
= 1;
    GetResult();
}


function RemoveRow()
{
    
//保留第一行表头,其余数据均删除.
    var iRows = document.getElementById("myTable").rows.length;
    
for(var i=0;i<iRows-1;i++)
    
{
        document.getElementById(
"myTable").deleteRow(1);
    }

}


function changeRecPerPage()
{
    recordsonpage 
= parseInt(document.getElementById("recordsperpage").value);
    GetResult();
}


function refresh()
{
    refreshflag 
= (refreshflag + 1% 2;

    
var obj = document.getElementById('autoRefresh');
    
var timeInterval;
    
    
if(refreshflag == 1)
    
{
        
var timeout = parseInt(document.getElementById("timeInterval").value)
        parent.timeInterval 
=  timeout ? timeout : 30
        obj.value 
= "Stop Refresh";
        intervalID 
= window.setInterval("GetResult()", parseInt(parent.timeInterval) * 1000);
    }

    
else
    
{    if(intervalID != null)
            window.clearInterval(intervalID);
            
        obj.value 
= "Start Refresh";
    }

}

实验结果表明,采用AJAX框架以后,整个系统的性能优化了不少。^_^ 

附:XMLHTTPRequest中文参考手册

发表于 @ 2006年08月04日 15:10:00 | 评论( loading... ) | 编辑| 举报| 收藏

旧一篇:明晰C语言中的floor, ceil和type cast | 新一篇:JAVA--HelloWorld问题集精华

  • 发表评论
  • 评论内容:
  •  
Copyright © cquzjh
Powered by CSDN Blog