方案一:
瀏覽器由於安全的限制,不允許跨域訪問。但是PHP服務器是允許的。我們可以通過使用PHP文件做代理,通過PHP來調用接口。
詳細接口分析可參看:http://www.cnblogs.com/wangjingblogs/p/3192953.html
返回JSON格式
PHP代碼
<?php //此接口返回json格式 echo file_get_contents('http://www.weather.com.cn/data/cityinfo/101181601.html'); ?>
HTML代碼
<!DOCTYPE html> <html> <head> <title>調用天氣預報接口</title> </head> <body> <script type="text/javascript"> window.onload = function () { //創建XMLHttpRequest對象 var xmlHttp = new XMLHttpRequest(); //創建連接 xmlHttp.open('get','./getWeather.php'); //判斷准備狀態及狀態碼 xmlHttp.onreadystatechange = function(){ if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { //把后台傳來的字符串類型的數據信息轉換成對象 eval('var info ='+ xmlHttp.responseText); //把weatherinfo對象中的數據存放到info中 info = info.weatherinfo; console.log(info); //拼接字符串 var str = ''; str += '城市:'+info.city+'<br>'; str += '城市編號:'+info.cityid+'<br>'; str += '溫度:'+info.temp1+'~'+info.temp2+'<br>'; str += '天氣:'+info.weather+'<br>'; str += '發布時間:'+info.ptime+'<br>'; //把數據輸出到瀏覽器 document.getElementById('weather').innerHTML = str; } } //發送連接 xmlHttp.send(null); } </script> <div id="weather"> <!-- 此處顯示天氣預報 --> </div> </body> </html>
方案二:
為天氣預報接口,可直接將以上代碼放到項目中直接使用!
<iframe name=\"weather_inc\" src=\"http:\/\/i.tianqi.com\/index.php?c=code&id=1\" width=\"330\" height=\"35\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\"><\/iframe>
完整代碼:
<!DOCTYPE html> <html> <head> <title>調用天氣預報接口</title> </head> <script type="text/javascript"> document.writeln("<iframe name=\"weather_inc\" src=\"http:\/\/i.tianqi.com\/index.php?c=code&id=1\" width=\"330\" height=\"35\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\"><\/iframe>"); </script> <body> <!-- 天氣預報接口 --> <iframe width="420" scrolling="no" height="60" frameborder="0" allowtransparency="true" src="http://i.tianqi.com/index.php?c=code&id=17&icon=1&num=3"></iframe> </body> </html>
另外,還有一些網站提供了免費的接口調用,很方便,可自定義天氣預報樣式並生成相應的代碼,放在項目中即可直接使用
http://www.tianqi.com/plugin/
http://www.cnblogs.com/wangjingblogs/p/3192953.html