为了提高网页速度,我计划是使用Ajax、PHP、javascript来实现异步操作,就是每次打开网页后,网页发送一个消息给服务器,服务器自己运行一个程序,这里是runonserver.php,更新内容,等网页刷新时,从服务器获取新的网页内容,这样可以提高网页的速度。
代码如下:
我发现如果传给服务器的字符串相同,服务器的runonserver.php就不运行,所以就用PHP的函数获得当前的时间,作为字符串发给服务器端。下面的代码是每次页面得到焦点,就会发消息给服务器,服务器的runonserver.php就运行一次。
客户端代码:
<html>
<head>
</head>
<body onFocus="showHint('<?php echo time(); ?>')">
<p>The information from the server: <span id="txtHint"></span></p>
</body>
<script type="text/javascript">
function showHint(str)
{
var xmlhttp;
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","runonserver.php?q="+str,true);
xmlhttp.send();
}
</script>
</html>
服务器端代码:
<?php
// 这里省略的,反馈的消息hello会显示在客户端的页面上。
echo "hello";
?>
打开客户端网页,显示:
The information from the server: hello