调用天气预报接口

方案一:

浏览器由于安全的限制,不允许跨域访问。但是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

原文地址:https://www.cnblogs.com/zxf100/p/6741287.html