<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>天氣預報</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <meta http-equiv="Content-type" content="text/html;charset=utf-8" /> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <script type="text/javascript"> <!-- //abc()表示要調用函數,5000表示每隔3秒去調用abc(); //第一步-------------------------------------------------------建立ajax引擎 function getXmlHttpObject(){ var xmlHttpRequest; //不一樣的瀏覽器獲取對象xmlhttprequest 對象方法不同 if(window.ActiveXObject){ xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP");//這個是ie內核 }else{ xmlHttpRequest=new XMLHttpRequest();//非ie內核 } return xmlHttpRequest;//將建立建立的ajax引擎實例化 } var myXmlHttpRequest="";//設置全局變量 爲了後面的chuli 函數須要取得屬性 //第二步----------------------------------------------------------------------獲取數據併發送服務器 function sendRequest(){ myXmlHttpRequest=getXmlHttpObject();//從實例化的模型裏面的方法函數 if(myXmlHttpRequest){ var url="doweather.php";//url 屬性 選擇提交的地址 var data="city[]=bj&city[]=sh&city[]=cd"//數據 id爲sheng的數據取得數據 myXmlHttpRequest.open("post",url,true);//這裏選擇提交的方式post 異步操做 myXmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//打開請求. //指定爲了第四步處理作準備回調函數.chuli是函數名 myXmlHttpRequest.onreadystatechange=function chuli(){ if(myXmlHttpRequest.readyState==4){ if(myXmlHttpRequest.status==200){ var res_obj=eval("("+myXmlHttpRequest.responseText+")"); $('bj').innerText=res_obj[0].price; $('sh').innerText=res_obj[1].price; $('cd').innerText=res_obj[2].price; } } } myXmlHttpRequest.send(data); //第二部--------------------------發送數據到服務器端 } } function $(id){ return document.getElementById(id); } window.setInterval("sendRequest()",1000); --> </script> </head> <body> <center> <h1>每隔5秒中更新數據</h1> <table border="1"> <tr><td>城市</td><td>溫度</td></tr> <tr><td >北京</td><td id="bj">21℃</td></tr> <tr><td >上海</td><td id="sh">20℃</td></tr> <tr><td >成都</td><td id="cd">11℃</td></tr> </table> </center> </body> </html>
<?php header("Content-Type: text/html;charset=utf-8"); //告訴瀏覽器不要緩存數據 header("Cache-Control: no-cache"); //獲取城市的名字 $cities=$_POST['city']; $res='['; for($i=0;$i<count($cities);$i++){ if($i==count($cities)-1){ $res.='{"cityname":"'.$cities[$i].'","price":"'.rand(0,40).'℃"}]'; }else{ $res.='{"cityname":"'.$cities[$i].'","price":"'.rand(0,40).'℃"},'; } } echo $res; ?>