javascript中天气接口案例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>天气预报</title>
    <style>
        table {
            margin-top: 20px;
            width: 600px;
            border-collapse: collapse;
        }
        td,th{
            height: 50px;
            text-align: center;
            border: 1px solid #CCC;
        }
    </style>
</head>
<body>
<input type="text" id="city"/> <a href="javascript:;" id="search">天气查询</a>
<table>
    <thead>
    <tr>
        <th>日期</th>
        <th>白天</th>
        <th>晚上</th>
        <th>温度</th>
        <th>天气</th>
        <th>风力</th>
    </tr>
    </thead>
    <tbody>
    </tbody>
</table>
<script type="text/template" id="template">
    <%for(var i = 0 ; i < model.length ; i++){%>
        <tr>
            <td><%=model[i].date%></td>
            <td><img src="<%=model[i].dayPictureUrl%>" alt=""/></td>
            <td><img src="<%=model[i].nightPictureUrl%>" alt=""/></td>
            <td><%=model[i].temperature%></td>
            <td><%=model[i].weather%></td>
            <td><%=model[i].wind%></td>
        </tr>
    <%};%>
</script>
<script src="./js/jquery.min.js"></script>
<script src="./js/template-native.js"></script>
<script>
    $(function(){
        /*
        * 1.输入城市名
        * 2,点击的时候发送请求
        * 3.响应成功渲染页面
        * */
        $('#search').on('click',function(){
            var city = $('#city').val()||'北京';
            $.ajax({
                type:'get',
                url:'http://api.map.baidu.com/telematics/v3/weather?output=json&ak=0A5bc3c4fb543c8f9bc54b77bc155724',
                data:{location:city},
                dataType:'jsonp',
                success:function(data){
                    var weather_data = data.results[0].weather_data;
                    
                    var html = template('template',{model:weather_data});
                    $('tbody').html(html);
                }
            });
        });
    });
</script>
</body>
</html>

 

posted @ 2016-09-27 20:52  萧诺  阅读(4807)  评论(1编辑  收藏  举报