聚合數據全國天氣預報--ajax 通過城市名取數據

聚合數據天氣預報API:https://www.juhe.cn/docs/api/id/39

接口地址:http://v.juhe.cn/weather/index
支持格式:json/xml
請求方式:get
請求示例:http://v.juhe.cn/weather/index?format=2&cityname=%E8%8B%8F%E5%B7%9E&key=您申請的KEY
調用樣例及調試工具:API測試工具
請求參數說明:
  名稱 類型 必填 說明
  cityname string Y 城市名或城市ID,如:"蘇州",需要utf8 urlencode
  dtype string N 返回數據格式:json或xml,默認json
  format int N 未來6天預報(future)兩種返回格式,1或2,默認1
  key string Y 你申請的key
HTML部分代碼:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" >
    <title>天氣預報</title>
    <script src="jquery-2.1.1.min.js"></script>
    <link rel="stylesheet" href="w.css">
</head>
<body>

<div id="mf_weather">
    <script src="w.js"></script>
    <button id="search">天氣查詢</button>
    <input id="city" type="text" value="tbody">
    <div class="ctn">
    <div id="mufeng">

    </div>
        <div id="future"></div>
    </div>    
</div>

</body>
</html>

JavaScript部分:

$(function(){
        /*
        * 1.輸入城市名
        * 2,點擊的時候發送請求
        * 3.響應成功渲染頁面
        * */

        $('#search').on('click',function(){

            var city = $('#city').val()||'北京';
            $citycode=urlencode(city);

 url='http://v.juhe.cn/weather/index?format=2&cityname='+$citycode+'&key=c82727e986a4f6cfc6ba1984f1f9183a';
             $.ajax({url: url,
                 dataType: "jsonp",
                type:"get",

                 data:{location:city},
                success:function(data){
                    var sk = data.result.sk;
        var today = data.result.today;
        var futur = data.result.future;
        var fut = "日期溫度天氣風向";
                   $('#mufeng').html("<p>" + '當前:  ' + sk.temp + '℃  , ' + sk.wind_direction + sk.wind_strength + ' , ' + '空氣溼度' + sk.humidity + ' , 更新時間' + sk.time + "</p><p style='padding-bottom: 10px;'>" + today.city + ' 今天是:  ' + today.date_y + ' ' + today.week + ' , ' + today.temperature + ' , ' + today.weather + ' , ' + today.wind + "<p></p>");

   $('#future').html("<p>" + '未來:  ' + futur[0].temperature+ '℃  , ' + futur[0].weather + futur[0].wind + ' , ' + ' , 更新時間' + futur[0].week+futur[0].date + "</p><p style='padding-bottom: 10px;'>" + today.city + "<p></p>");

           }     });

        });
  function urlencode (str) {  
    str = (str + '').toString();   

    return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').  
    replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');  
} 
})

預覽圖(比較簡單粗糙)

 輸入圖片說明


文章來源:https://my.oschina.net/mfeng/blog/757756




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章