客户端文件weather.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html;charset=GBK" />
<script type="text/javascript">
function f1(){
//创建对象
//判断用户的浏览器,决定使用何种方式Ajax对象
if(typeof ActiveXObject != "undefined"){
var version = ['Msxm12.XMLHTTP.6.0','Msxm12.XMLHTTP.5.0','Msxm12.XMLHTTP.3.0','Msxm12.XMLHTTP','Microsoft.XMLHTTP'];
for(var i =0;i<=version.length;i++){
try{
var obj = new ActiveXObject(version[i]);
if(typeof obj != "undefined"){
break;
}
}
catch(ex){}
}
}else{
var obj = new XMLHttpRequest();
}
//感知Ajax状态
obj.onreadystatechange = function(){
if(obj.readyState==4 && obj.status==200){
//接收服务器返回的JSON格式的天气预报信息
eval(" var info ="+obj.responseText);
var ss="";
//拼接获得的天气信息字符串
ss += "地址:"+info.weatherinfo.city+"<br />";
ss += "温度:"+info.weatherinfo.temp+"<br />";
ss += "风向:"+info.weatherinfo.WD+"<br />";
//将天气信息字符串写入到HTML页面中
document.getElementById("result").innerHTML = ss;
}
}
//创建一个http请求,并设置“请求地址”
obj.open("get","./weather.php");
//发送请求
obj.send();
}
</script>
</head>
<body>
<h2>Ajax通过JSON接口获取天气预报信息</h2>
<div id="result"></div>
<input type="button" οnclick="f1()" value="触发天气" />
</body>
</html>
服务器端weather.php
<?php
//定义一个JSON接口的天气预报地址字符串
$url = "http://www.weather.com.cn/data/sk/101010100.html";
//将$url地址中的天气信息读入到一个字符串
$weatherinfo = file_get_contents($url);
//输出获得的JSON格式的天气信息
echo $weatherinfo;
?>