浏览器由于安全方面的问题,禁止ajax跨域请求其他网站的数据
解决:利用本域php代理间接获取weather.php
<?php
header("content-type:text/html;charset=utf-8");
//php代理获取天气信息
//跨域请求
//天气预报接口
$url = "http://www.weather.com.cn/data/sk/101010100.html";
$cont = file_get_contents($url);
echo $cont;
?>
ajax通过php代理获取天气信息
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" >
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
<title>ajax</title>
<style type="text/css">
</style>
<script type="text/javascript">
function getWeather(){
var xhr = new XMLHttpRequest();
var s = "";
xhr.onreadystatechange = function(){
if(xhr.readyState==4){
alert(xhr.responseText);
eval("var info="+xhr.responseText);
s += "城市:"+info.weatherinfo.city+" ";
s += "温度:"+info.weatherinfo.temp+" ";
s += "风向:"+info.weatherinfo.WD+" ";
s += "风力:"+info.weatherinfo.WS;
}
document.getElementById("weather").innerHTML = s;
}
xhr.open('get','./weather.php');
xhr.send(null);
//阻止浏览器默认动作 跳转
return false;
}
</script>
</head>
<body>
<h2>ajax无刷新获取天气信息</h2>
<input type="submit" value="获取天气" οnclick="getWeather()"></input>
<div id="weather"></div>
<hr/>
<iframe width="420" scrolling="no" height="60" frameborder="0" allowtransparency="true" src="http://i.tianqi.com/index.php?c=code&id=12&icon=1&num=5"></iframe>
</body>
</html>