跨域請求:查詢天氣

例:http://tianqi.2345.com/t/shikuang/57083.js?1507707799100
response:var weatherinfovar = {"weatherinfo":{"city":"\u90d1\u5dde","cityid":"101180101","temp":"13","SD":"82%","WD":"\u4e1c\u5317\u98ce","WS":"1\u7ea7","QY":"1026","JS":"\u964d\u6c34\u6982\u7387: 59%","pm25":"22","idx":"39","lv_hint":"\u4f18","aqiLevel":1}};

解析後:weatherinfo:
JS: "降水概率: 59%"
QY: "1026"(氣壓)
SD: "82%" (溼度)
WD: "東北風"
WS: "1級"
aqiLevel: 1
city: "鄭州"
cityid: "101180101"
idx: "39"
lv_hint: "優"
pm25: "22"
temp: "13"(當前溫度)
__proto__: Object

分析url:‘57083’是城市的編號,?1507707799100:時間戳

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>跨域請求2</title>
    <script type="text/javascript" src="/static/js/jquery-1.12.4.min.js"></script>
    <script type="text/javascript" src="http://tianqi.2345.com/t/map_js/china.js"></script>
    <script type="text/javascript" src="http://tianqi.2345.com/t/shikuang/57083.js" id="change"></script>
    <script type="text/javascript">
        //weatherinfovar:鄭州天氣  chinaWeaInfo:全國天氣
        console.log(weatherinfovar);
        //獲取各省會城市的cityid 和 name,並轉換爲json對象
        var cityidinfo ="{";
        $.each(chinaWeaInfo,function(index,item){
            cityidinfo += '"' + item.name +'"'+ ':' +'"'+ index +'"' +',';
        });
        cityidinfo = cityidinfo.slice(0,-1) + "}";
        cityidinfo = JSON.parse(cityidinfo);

        weather = weatherinfovar.weatherinfo;
        $(function () {
            weatherinfo(weather);
            $('#search').click(function () {
                //console.log($('#change').attr('src'));
                sendrequest(cityidinfo[$('#cityid').val()])
            })
        });
        //顯示天氣
        function weatherinfo(weather) {
            var msg = '';
            msg += '城市: ' + weather.city +'<br>';
            msg += '當前溫度: ' + weather.temp + '℃<br>';
            msg += '溼度: ' + weather.SD + '<br>';
            msg += '風力: ' + weather.WD + weather.WS + '<br>';
            msg += '氣壓: ' + weather.QY + 'hPa<br>';
            msg += '空氣質量: ' + weather.lv_hint;
            $('#weatherinfo').html(msg)
        }

        //發送ajax請求
        function sendrequest(cityid) {
            var src;
            //設置請求url
 src = "http://tianqi.2345.com/t/shikuang/" +cityid+ ".js?t=" + new Date().getTime(); $('#change').attr({'src':src}); //$.getJSON(src+'format =json&jsoncallback=?'); $.ajax({ url:src, dataType:'jsonp', complete:function (xhr,status) { console.log(status); console.log(weatherinfovar); weatherinfo(weatherinfovar.weatherinfo); } }); } </script></head><body><input type="text" name="cityid" id="cityid"><input type="button" value="查詢" id="search"><br><div id="weatherinfo"></div></body></html>


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